普通对象使用spring容器中的对象

引语:

    工做中有时候须要在普通的对象中去调用spring管理的对象,可是在普通的java对象直接使用@Autowired或者@Resource的时候会发现被注入的对象是null,会报空指针。咱们能够简单的理解为spring是一个公司,它管理的对象就是它的员工,而普通的java对象是其余公司的员工,若是其余公司要找spring公司的员工一块儿共事没有通过spring公司的赞成确定是不行的。html

解决方式:

方法一:若是这个普通对象能够被spring管理的话,最好是直接交给spring管理,这样spring管理的bean中注入其余的bean是没有问题的。java

方法二:当咱们的普通对象没有办法交给spring管理的时候,咱们能够建立一个公共的springBeanUtil专门为普通对象提供spring的员工(有点像spring公司的外包部门,把对象外包给其余公司使用,哈哈)。spring

@Service
public class SpringBeanUtil implements ApplicationContextAware {

    public static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        applicationContext = context;
    }

    // 这里使用的是根据class类型来获取bean 固然你能够根据名称或者其余之类的方法 主要是有applicationContext你想怎么弄均可以
    public static Object getBeanByClass(Class clazz) {
        return applicationContext.getBean(clazz);
    }
}

这个util呢,其实就是实现了ApplicationContextAware接口,有小伙伴要问了这个接口是干吗的?这里给出连接地址,ApplicationContextAware参考资料。而后我也将文档中的解释给摘录过来了api

public interface ApplicationContextAware extends Aware
Interface to be implemented by any object that wishes to be notified of the ApplicationContext that it runs in.
Implementing this interface makes sense for example when an object requires access to a set of collaborating beans. Note that configuration via bean references is preferable to implementing this interface just for bean lookup purposes.
This interface can also be implemented if an object needs access to file resources, i.e. wants to call getResource, wants to publish an application event, or requires access to the MessageSource. However, it is preferable to implement the more specific ResourceLoaderAware, ApplicationEventPublisherAware or MessageSourceAware interface in such a specific scenario.
Note that file resource dependencies can also be exposed as bean properties of type Resource, populated via Strings with automatic type conversion by the bean factory. This removes the need for implementing any callback interface just for the purpose of accessing a specific file resource.
ApplicationObjectSupport is a convenience base class for application objects, implementing this interface.

大概意思就是说只要实现了ApplicationContextAware接口的类,指望被告知当前运行的applicationContext是什么。而后又说了若是是想要获取资源最好是用ResourceLoaderAware, ApplicationEventPublisherAware or MessageSourceAware 这几个接口,最后还来了一句咱们知道大家要使用这些接口,因此咱们帮你弄了一个实现了这些接口的抽象类ApplicationObjectSupport(在spring-context的jar包中)。这里说得很清楚要使用bean的话,实现ApplicationContextAware,由于咱们这里不须要使用静态资源之类的因此咱们就不用spring为咱们提供的ApplicationObjectSupport了,有兴趣的能够本身研究下。app

咱们这里简单的看一下ApplicationContextAware类里面都有啥?ide

void setApplicationContext(ApplicationContext applicationContext) throws BeansException;

发现就一个方法,spring初始化的时候会将当前的applicationContext传给ApplicationContextAware的setApplicationContext方法,因此只要实现类将这个applicationContext拿到了,就能够经过class类型或者class的名称来获取到spring中的bean了。原理其实很简单吧。使用的时候咱们能够调用spring中的bean。以下:ui

Test test = (Test) SpringBeanUtil.getBeanByClass(Test.class);
相关文章
相关标签/搜索