spring初始化加載InitializingBean

最近在爲公司一個創新項目,其中用到spring的初始技術,先做一個總結。
spring初始化bean有兩種方式:
第一:實現InitializingBean接口,繼而實現afterPropertiesSet的方法
第二:反射原理,配置文件使用init-method標籤直接注入bean

<bean id="testInitializingBean" class="com.TestInitializingBean" init-method="testInit"></bean>

不同點:
接口比配置效率高,但是配置消除了對spring的依賴。

這裏詳解如何使用接口方式實現spring初始化bean。

第一步:新建測試類TestGate,其中Intent是一個接口,有幾個實現類就會被初始化幾個實例

@Component//代表將這個類注入spring容器中
public class TestGate implements InitializingBean,ApplicationContextAware {

    private ApplicationContext applicationContext;
//實現afterPropertiesSet,可以寫初始化bean
    @Override
    public void afterPropertiesSet() throws Exception {
          Map<String,Intent> map= applicationContext.getBeansOfType(Intent.class);
    }
//使用ApplicationContextAware實現spring上下文對象初始化賦值
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext=applicationContext;
    }
}

二、通過@component將TesGate注入spring容器中或者使用

<bean id="testGate" class=""/>

三、web.xml文件配置監聽

<!-- 初始化Spring容器,讓Spring容器隨Web應用的啓動而自動啓動 -->  
    <listener>  
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
    </listener>  

四、在項目中可以獲得接口intent的幾個實現類bean對象
這裏寫圖片描述

發佈了63 篇原創文章 · 獲贊 17 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章