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

引語:

    工作中有時候需要在普通的對象中去調用spring管理的對象,但是在普通的java對象直接使用@Autowired或者@Resource的時候會發現被注入的對象是null,會報空指針。我們可以簡單的理解爲spring是一個公司,它管理的對象就是它的員工,而普通的java對象是其他公司的員工,如果其他公司要找spring公司的員工一起共事沒有經過spring公司的同意肯定是不行的。

解決方式:

方法一:如果這個普通對象可以被spring管理的話,最好是直接交給spring管理,這樣spring管理的bean中注入其他的bean是沒有問題的。

方法二:當我們的普通對象沒有辦法交給spring管理的時候,我們可以創建一個公共的springBeanUtil專門爲普通對象提供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參考資料。然後我也將文檔中的解釋給摘錄過來了

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了,有興趣的可以自己研究下。

我們這裏簡單的看一下ApplicationContextAware類裏面都有啥?

void setApplicationContext(ApplicationContext applicationContext) throws BeansException;

發現就一個方法,spring初始化的時候會將當前的applicationContext傳給ApplicationContextAware的setApplicationContext方法,所以只要實現類將這個applicationContext拿到了,就可以通過class類型或者class的名稱來獲取到spring中的bean了。原理其實很簡單吧。使用的時候我們可以調用spring中的bean。如下:

Test test = (Test) SpringBeanUtil.getBeanByClass(Test.class);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章