轉(zhuǎn)自: http://www.blogjava.net/cmzy/archive/2008/07/29/218059.html
- /**
- *
- */
- package ioc.test;
- /**
- *@authorzhangyong
- *
- */
- public class Animal{
- private Stringname;
- private int age;
- public Stringspeak(){
- return "我的名字:" + this .name+ ",我的年齡:" + this .age;
- }
- public void init_xx() throws Exception{
- System.out.println( "初始化方法start()正在運(yùn)行!" );
- }
- public void end() throws Exception{
- System.out.println( "析構(gòu)方法end()正在運(yùn)行!" );
- }
- //Geter和Seter省略
- }
配置文件中配置好bean,并為其指定響應(yīng)的預(yù)處理方法和析構(gòu)方法:
這里的init_xx方法在實(shí)例化與依賴注入之前被調(diào)用,end方法在銷毀之前調(diào)用
- <? xml version = "1.0" encoding = "UTF-8" ?>
- < beans
- xmlns = "http://www.springframework.org/schema/beans"
- xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation ="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-2.5.xsd" >
- < bean id = "animal" class = "ioc.test.Animal" init-method = "init_xx" destroy-method = "end" >
- < property name = "age" value = "5" > </ property >
- < property name = "name" value = "豬" > </ property >
- </ bean >
- </ beans >
創(chuàng)建含有主方法的測試類,代碼如下:
- /**
- *
- */
- package ioc.test;
- import org.springframework.context.support.AbstractApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- /**
- *@authorzhangyong
- *
- */
- public class TestMain{
- public static void main(String[]args){
- AbstractApplicationContextac= new ClassPathXmlApplicationContext( "applicationContext.xml" );
- //注冊容器關(guān)閉鉤子,才能關(guān)掉容器,調(diào)用析構(gòu)方法
- ac.registerShutdownHook();
- Animalanimal=ac.getBean( "animal", Animal.class );
- System.out.println(animal.speak());
- }
- }
運(yùn)行主類,結(jié)果如下:
需要注意的是:要看到析構(gòu)方法的輸出,也必須要注冊關(guān)閉鉤子。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
