bean初始化和銷毀方法的幾種實現(xiàn)

第一種方法,繼承InitializingBean和DisposableBean方法
繼承前者實現(xiàn)afterPropertiesSet方法,繼承后者實現(xiàn)destroy方法,
代碼示例:
定義一個實體類:

public class Info {
}

定義另一個實體類實現(xiàn)InitializingBean和DisposableBean接口:

public class Bus implements InitializingBean,DisposableBean {

    private Info info;

    public void setInfo(Info info) {
        System.out.println("setInfo");
        this.info = info;
    }

    public Info getInfo() {
        return info;
    }

    public Bus(){
        System.out.println("bus constr");
    }

    //InitializingBean的方法
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("==============afterPropertiesSet==========");
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("=================destroy===================");
    }
}

配置類:

@Configuration
public class AppContext {

    @Bean
    public Info info(){
        return new Info();
    }

    @Bean
    public Bus createBus(){
        Bus bus = new Bus();
        bus.setInfo(info());
        return bus;
    }
}

測試類:

public class Test {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppContext.class);
        Bus bus = context.getBean(Bus.class);
        System.out.println(bus);
        context.close();
    }
}

測試結果:

bus constr
setInfo
==============afterPropertiesSet==========
com.zhihao.miao.bean.demo4.Bus@73d4cc9e
=================destroy===================

我們發(fā)現(xiàn)繼承InitializingBean接口實現(xiàn)的afterPropertiesSet方法在屬性設置之后執(zhí)行畜号,繼承DisposableBean接口實現(xiàn)destroy方法在對象銷毀之后執(zhí)行尿这。

InitializingBean接口

Interface to be implemented by beans that need to react once all their properties have been set by a BeanFactory: for example, to perform custom initialization, or merely to check that all mandatory properties have been set.
這個接口的實現(xiàn)在所有屬性被BeanFactory設置之后才被執(zhí)行:比如說簇抵。執(zhí)行自定義的初始化或者檢查雖有必要的屬性是否被設置。

An alternative to implementing InitializingBean is specifying a custom init-method, for example in an XML bean definition. For a list of all bean lifecycle methods, see the BeanFactory javadocs.
實現(xiàn)InitializingBean的替代方法是指定一個自定義的init方法射众,例如在一個XML bean定義中碟摆。 有關所有bean生命周期的方法,請參閱BeanFactory 幫助文檔

DisposableBean接口

Interface to be implemented by beans that want to release resources on destruction. A BeanFactory is supposed to invoke the destroy method if it disposes a cached singleton. An application context is supposed to dispose all of its singletons on close.
這個接口的實現(xiàn)在bean實例被銷毀的時候釋放資源被調用叨橱。BeanFactory支持調用destroy方法處理緩存單列典蜕。

An alternative to implementing DisposableBean is specifying a custom destroy-method, for example in an XML bean definition. For a list of all bean lifecycle methods, see the BeanFactory javadocs.
實現(xiàn)DisposableBean的替代方法是指定一個自定義的destroy方法,例如在XML bean定義罗洗。 有關所有bean生命周期方法愉舔,請參閱BeanFactory 幫組文檔。

第二種方式使用@Bean注解的參數(shù)
定義一個實例類伙菜,并在實例類中定義初始化方法和銷毀方法

public class Bike {
    public void init(){
        System.out.println("=== bike ===init ====");
    }

    public void destroy() {
        System.out.println("===== bike ===destroy ====");
    }

}

定義一個AppContext類轩缤,用@Configuration注解標記一下

@Configuration
public class AppContext {

    @Bean(initMethod="init",destroyMethod="destroy")
    public Bike createBike(){
        return new Bike();
    }
}

測試:

public class Test {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppContext.class);
        System.out.println(context.getBean(Bike.class));
        context.close();
    }
}

執(zhí)行結果:

=== bike ===init ====
com.zhihao.miao.bean.demo5.Bike@68ceda24
===== bike ===destroy ====

第三種使用@PostConstruct和@PreDestroy注解
定義一個實體類:

public class Train {

    @PostConstruct
    public void initial(){
        System.out.println("......initial......");
    }

    @PreDestroy
    public void close(){
        System.out.println("......close.........");
    }

}

定義一個實體類,配置了@Configuration注解:

@Configuration
public class AppContext {

    @Bean
    public Train createTrain(){
        return new Train();
    }

}

測試:

public class Test {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppContext.class);
        System.out.println(context.getBean(Train.class));
        context.close();
    }
}

測試結果:

......initial......
com.zhihao.miao.bean.demo6.Train@4516af24
......close.........
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末贩绕,一起剝皮案震驚了整個濱河市典奉,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌丧叽,老刑警劉巖,帶你破解...
    沈念sama閱讀 211,123評論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件公你,死亡現(xiàn)場離奇詭異踊淳,居然都是意外死亡,警方通過查閱死者的電腦和手機陕靠,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,031評論 2 384
  • 文/潘曉璐 我一進店門迂尝,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人剪芥,你說我怎么就攤上這事垄开。” “怎么了税肪?”我有些...
    開封第一講書人閱讀 156,723評論 0 345
  • 文/不壞的土叔 我叫張陵溉躲,是天一觀的道長。 經(jīng)常有香客問我益兄,道長锻梳,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,357評論 1 283
  • 正文 為了忘掉前任净捅,我火速辦了婚禮疑枯,結果婚禮上,老公的妹妹穿的比我還像新娘蛔六。我一直安慰自己荆永,他們只是感情好废亭,可當我...
    茶點故事閱讀 65,412評論 5 384
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著具钥,像睡著了一般豆村。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上氓拼,一...
    開封第一講書人閱讀 49,760評論 1 289
  • 那天你画,我揣著相機與錄音,去河邊找鬼桃漾。 笑死坏匪,一個胖子當著我的面吹牛,可吹牛的內容都是我干的撬统。 我是一名探鬼主播适滓,決...
    沈念sama閱讀 38,904評論 3 405
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼恋追!你這毒婦竟也來了凭迹?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 37,672評論 0 266
  • 序言:老撾萬榮一對情侶失蹤苦囱,失蹤者是張志新(化名)和其女友劉穎嗅绸,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體撕彤,經(jīng)...
    沈念sama閱讀 44,118評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡鱼鸠,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 36,456評論 2 325
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了羹铅。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片蚀狰。...
    茶點故事閱讀 38,599評論 1 340
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖职员,靈堂內的尸體忽然破棺而出麻蹋,到底是詐尸還是另有隱情,我是刑警寧澤焊切,帶...
    沈念sama閱讀 34,264評論 4 328
  • 正文 年R本政府宣布扮授,位于F島的核電站,受9級特大地震影響专肪,放射性物質發(fā)生泄漏糙箍。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 39,857評論 3 312
  • 文/蒙蒙 一牵祟、第九天 我趴在偏房一處隱蔽的房頂上張望深夯。 院中可真熱鬧,春花似錦、人聲如沸咕晋。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,731評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽掌呜。三九已至滓玖,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間质蕉,已是汗流浹背势篡。 一陣腳步聲響...
    開封第一講書人閱讀 31,956評論 1 264
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留模暗,地道東北人禁悠。 一個月前我還...
    沈念sama閱讀 46,286評論 2 360
  • 正文 我出身青樓,卻偏偏與公主長得像兑宇,于是被迫代替她去往敵國和親碍侦。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 43,465評論 2 348

推薦閱讀更多精彩內容