spring多配置文件加载

在项目中会涉及到多个spring的配置文件,在我所接触的项目中,只用到了两种不同的方法进行配置,有其他好办法的,欢迎讨论。
方法一:
在web.xml文件中作如下配置:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext-*.xml,classpath*:applicationContext-*.xml</param-value>
</context-param>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

用ContextLoaderListener跟contextConfigLocation配合使用,contextConfigLocation用来指定系统配置文件的名称跟路径,ContextLoaderListener为监听器,这个就不多说了。
这个方式的优点是比较优雅,通俗易懂,不用修改什么代码。

方法二:
把几个配置文件写到一个配置文件中:
如创建这样一个配置文件:BeanRefFactory.xml
在这个配置文件里配置如下:
<beans>
<bean id="default" class="org.springframework.context.support.ClassPathXmlApplicationContext">
<constructor-arg>
<list>
<value>applicationContext.xml</value>
<value>applicationContext-business.xml</value>
<value>applicationContext-scheduler.xml</value>
</list>
</constructor-arg>
</bean>
</beans>

然后在web.xml文件中,使用自己定义一个ContextLoaderServlet来启动,这个ContextLoaderServlet可以继承HttpServlet,然后在它的init()方法里取得BeanFactory,代码如下:

public class ContextLoaderServlet extends HttpServlet
{
public ContextLoaderServlet()
{
}

public void init()
throws ServletException
{
//这个参数里的名字就是我们在BeanRefFactory.xml里定义的bean的名字。
DefaultBeanFactory.getFactory("default");
}

public void destroy()
{
}
}

然后定义一个DefaultBeanFactory类:
public class DefaultBeanFactory
{
protected static final BeanFactory getFactory(String s)
{
BeanFactoryLocator beanfactorylocator = SingletonBeanFactoryLocator.getInstance();
BeanFactoryReference beanfactoryreference = beanfactorylocator.useBeanFactory(s);
return beanfactoryreference.getFactory();
}
}


最后在web.xml文件中配置如下:
<servlet>
<servlet-name>context</servlet-name>
<servlet-class>com.lixh.web.servlet.ContextLoaderServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

这种方式改动较多,也比较麻烦,但是可以根据自己的需要随机加载信息。

我还看到过一种方式,就是配置
<servlet>
<servlet-name>test</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servelt>

后来查看资料发现这是spring MVC的用法,本人没用过spring MVC,在这里贴出来是不想把这些方式混淆,有个说明罢了。

posted @ 2009-12-22 10:51  hibernate3例子  阅读(929)  评论(0编辑  收藏  举报