获取Spring上下文

百度百科: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() 就能拿到了。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值