如果要在服务器启动时自动加载spring容器的话,那可定要在web.xml中配置。那么如何配置呢?请看下面代码
第一种:
没有任何的参数,直接通过监听器加载spring容器,这时候默认的读取路径是读取WEB-INF/applicationContext.xml,也就是说spring容器的配置文件只能有一个且名字必须为applicationContext.xml
<!-- 通过这个监听器来自动对spring的ApplicationContext进行加载 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
第二种:
手动指定参数,改变默认的读取路径,允许多文件读取构成spring容器,像下面这样的话applicationContext1.xml,applicationContext2.xml都能被读进去。
<context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext*.xml</param-value> </context-param> <!-- 通过这个监听器来自动对spring的ApplicationContext进行加载 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
那么服务器端怎么使用spring容器呢,如果是Action的话,只需要在Action上定义好与spring容器中bean的id相同的属性,action就会自动装配。如果是Servlet的话,那该怎么做呢?请看如下代码:
private ApplicationContext context;
//spring与Servlet整合的时候,因为Servlet和Filter不能进行自动装配,因此要用Servlet的init()的方法进行手动的赋值
@SuppressWarnings("unchecked")
@Override
public void init() throws ServletException
{
//hibernateTemplate对象还是从spring容器中获取因为服务器与数据库的连接一个
context=WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext());
ht=(HibernateTemplate)context.getBean("ht");
hibernateTrans=(UserDaoInterface)context.getBean("hibernateTrans");
};