百度百科:http://baike.baidu.com/view/9188914.htm
一、慎用 new ClassPathXmlApplicationContext
从类路径ClassPath中寻找指定的XML配置文件,找到并装载完成ApplicationContext的实例化工作。例如:
//装载单个配置文件实例化ApplicationContext容器
ApplicationContext cxt = new ClassPathXmlApplicationContext("applicationContext.xml");
//装载多个配置文件实例化ApplicationContext容器
String[] configs = {"bean1.xml","bean2.xml","bean3.xml"};
ApplicationContext cxt = new ClassPathXmlApplicationContext(configs);
new ClassPathXmlApplicationContext("applicationContext.xml")就是给所有的工厂管理BEAN分配内存。而如果上边代码不是单例或者使用该段代码的类不是单例,那就不停的给所配置BEAN分配内存。
而且即使是单例的也会加载两次,一次由spring加载,一次有new加载。
二、spring的ApplicationContextAware接口
在web工程里,有几个方法,我觉得这个方法最方便。
建个类,实现spring的ApplicationContextAware 接口,即
public class SpringContextTool implements ApplicationContextAware {
private static ApplicationContext context;
public void setApplicationContext(ApplicationContext acx) {
context = acx;
}
public static ApplicationContext getApplicationContext() {
return context;
}
}
然后在spring中定义这个bean,id随便给。用的时候直接SpringContextTool.getApplicationContext() 就能拿到了。