spring在web环境中,java代码里需要得到ApplicationContext; 根据前期配置的不同,有两种方式:
方式一,spring加载放到web.xml中配置:
<listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener>
则得到ApplicationContext用如下方式:
//在struts中需要实现ServletRequestAware类,便可得到request对象ServletContext s = ServletActionContext.getRequest().getSession().getServletContext();
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(s);
java代码中调用 ctx.getBean(String beanId);
方式二,直接声明:
public class BeanManager {private static ApplicationContext context = new ClassPathXmlApplicationContext("appcontext.xml") ;public static Object getBean(String beanId) {return context.getBean(beanId);}
}
在web.xml中写一个servlet,自动启动,init方法中调用一下BeanManager,为的是在Web应用启动的时候就让Spring加载bean配置文件,否则会在第一次调用BeanManager的时候加载,影响第一次访问速度。
init() throws ServletException {BeanManager bm = new BeanManager();}
在java代码中使用 BeanManager.getBean(String beanId); 来获得bean实例。
优缺点分析:
第一种方式需要在web容器下进行,不利于测试;
第二种方法与web容器无关,单元测试方便;