spring手动获取容器中的bean

只需要定义一个bean,这个bean继承ApplicationContextAware

如下:

public class SpringContextHolder implements ApplicationContextAware {  
    private static ApplicationContext applicationContext = null;  
  
    /** 
     * 获取静态变量中的ApplicationContext. 
     */  
    public static ApplicationContext getApplicationContext() {  
        assertContextInjected();  
        return applicationContext;  
    }  
  
    /** 
     * 从静态变量applicationContext中得到Bean, 自动转型为所赋值对象的类型. 
     */  
    @SuppressWarnings("unchecked")  
    public static <T> T getBean(String name) {  
        assertContextInjected();  
        return (T) applicationContext.getBean(name);  
    }  
  
    /** 
     * 从静态变量applicationContext中得到Bean, 自动转型为所赋值对象的类型. 
     */  
    public static <T> T getBean(Class<T> requiredType) {  
        assertContextInjected();  
        return applicationContext.getBean(requiredType);  
    }  
  
    /** 
     * 清除SpringContextHolder中的ApplicationContext为Null. 
     */  
    public static void clearHolder() {  
        applicationContext = null;  
    }  
  
    /** 
     * 实现ApplicationContextAware接口, 注入Context到静态变量中. 
     */  
    @Override  
    public void setApplicationContext(ApplicationContext applicationContext) {  
        SpringContextHolder.applicationContext = applicationContext;  
    }  
  
    /** 
     * 检查ApplicationContext不为空. 
     */  
    private static void assertContextInjected() {  
        Validate.validState(applicationContext != null,  
                "applicaitonContext属性未注入, 请在applicationContext.xml中定义SpringContextHolder.");  
    }  
  
}

把上述bean定义到spring.xml里头,那么

Spring容器会检测容器中的所有Bean,如果发现某个Bean实现了ApplicationContextAware接口,Spring容器会在创建该Bean之后,自动调用该Bean的setApplicationContextAware()方法,调用该方法时,会将容器本身作为参数传给该方法——该方法中的实现部分将Spring传入的参数(容器本身)赋给该类对象的applicationContext实例变量,因此接下来可以通过该applicationContext实例变量来访问容器本身。

工具使用

SpringContextHolder.getBean("beanName");

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

独行侠_阿涛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值