如何随时的获取Spring的ApplicaitonContext和Spring管理的Bean

@Autowired

1.需求:

在平时代码中 我们都是通过 @Autowired 来引入一个对象。也就是Spring的依赖注入。

不过使用依赖注入需要满足两个条件,注入类 和被注入类 都需要交给Spring去管理,也就是需要在Spring中配置Bean

但是开发中,有些工具类(或者实体类)是不需要在Spring中配置的,如果工具类里面 想引用Spring配置的Bean 应该怎么办

2.解决办法

2.1自己用的时候主动去new。 不可取 自己new的类 没有交给Spring去管理,如果类中 用到了Spring的一些注解功能 完全失效  

2.2 ApplicationContextAware接口

写一个SpringContextHolder专门去获取Spring管理的Bean。也就是说 被注入对象 可以不交给Spring管理,就可以获取Spring管理的Bean

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class SpringContextUtils implements ApplicationContextAware { 

    private static ApplicationContext applicationContext;
    /**
     * 如果实现了ApplicationContextAware接口,在Bean的实例化时会自动调用setApplicationContext()方法
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext)throws BeansException {
        SpringContextUtils.applicationContext = applicationContext;
    }
    
    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }


}

3.注意点

3.1 SpringContextUtils必须在Spring中配置bean(扫描还是bean配置都可以) 不然 在Bean的实例化时不会自动调用setApplicationContext()方法

扫描二维码关注公众号,回复: 1583690 查看本文章

3.2 SpringContextUtils中的ApplicationContext需要是static的

这样 我们就可在任何代码任何地方任何时候中取出ApplicaitonContext. 从而获取Spring管理的Bean

 

 

 

猜你喜欢

转载自www.cnblogs.com/ssskkk/p/9178338.html