轉自: 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()正在運行!" );
- }
- public void end() throws Exception{
- System.out.println( "析構方法end()正在運行!" );
- }
- //Geter和Seter省略
- }
配置文件中配置好bean,并為其指定響應的預處理方法和析構方法:
這里的init_xx方法在實例化與依賴注入之前被調用,end方法在銷毀之前調用
- <? 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 >
創建含有主方法的測試類,代碼如下:
- /**
- *
- */
- 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" );
- //注冊容器關閉鉤子,才能關掉容器,調用析構方法
- ac.registerShutdownHook();
- Animalanimal=ac.getBean( "animal", Animal.class );
- System.out.println(animal.speak());
- }
- }
運行主類,結果如下:
需要注意的是:要看到析構方法的輸出,也必須要注冊關閉鉤子。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

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