Spring中Bean获取IOC容器服务的方法

Spring 依赖注入可以让所有的Bean对其IOC容器的存在是没有意识的,甚至可以将容器换成其它的。但实际开发中如果某个Bean对象要用到Spring 容器本身的功能资源,需要意识到IOC容器的存在才能调用Spring所提供的资源应该如何处理呢?

一、使用@Autowired依赖注入

只有是在同一个IOC容器中,就可以通过@Autowired依赖注入获取到对应的Bean对象,如下:

@Autowired
private MessageSource messageSource; 

@Autowired
private ResourceLoader resourceLoader; 

@Autowired
private ApplicationContext applicationContext;

二、实现相应的Aware接口

Spring Aware接口的目的就是为了让Bean获取到IOC容器的各种服务,像是BeanFactoryAware、 BeanNameAware、ApplicationContextAware、ResourceLoaderAware、ServletContextAware等等。实现这些Aware接口的Bean在被实例化后可以获取相对应的资源,例如实现BeanFactoryAware的Bean在实例化后,Spring容器将会注入BeanFactory的实例,而实现ApplicationContextAware的Bean,在Bean被实例化后,将会被注入 ApplicationContext的实例等等。

如果要用在工具类静态方法中,一般采用实现接口的方式。如下:

@Service()
@Lazy(false)
public class SpringContextHolder implements ApplicationContextAware, DisposableBean {

    private static ApplicationContext applicationContext = null;

    /**
     * 实现ApplicationContextAware接口, 注入Context到静态变量中.
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        if (SpringContextHolder.applicationContext != null) {
            System.out.println("SpringContextHolder中的ApplicationContext被覆盖, 原有ApplicationContext为:" + SpringContextHolder.applicationContext);
        }
        System.out.println("Spring容器启动,将容器实例注入到SpringContextHolder实例bean中");
        SpringContextHolder.applicationContext = applicationContext;
    }/**
     * 取得存储在静态变量中的ApplicationContext.
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        return (T) applicationContext.getBean(name);
    }

    /**
     * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
     */
    public static <T> T getBean(Class<T> requiredType) {
        return applicationContext.getBean(requiredType);
    }
}
原文地址:https://www.cnblogs.com/doit8791/p/8879878.html