MyEclipse Spring 学习总结二 Bean的生命周期

本文通过一个具体的示例展示了如何在Spring框架中定义Bean的初始化(init-method)和销毁(destroy-method)方法。示例中使用了一个名为HelloWorld的类,并在applicationContext.xml中配置了这些生命周期方法。

文件结构可以参考上一节

Bean的生命周期有方法有:init-method,destroy-method

ApplicationContext.xml 文件配置如下:

1
2
3
4
5
6
7
8
9
10
11
<?xml version= "1.0"  encoding= "UTF-8" ?>
<beans
     xmlns= "http://www.springframework.org/schema/beans"
     xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"
     xmlns:p= "http://www.springframework.org/schema/p"
     xsi:schemaLocation= "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd" >
 
     <bean id= "helloWorld"  class = "bu.example.com.HelloWorld"   init-method= "init"  destroy-method= "destroy" >
         <property name= "message"  value= "Hello World!!!"  />
     </bean>
</beans>

  

MainApp.java 文件

1
2
3
4
5
6
7
8
public  static  void  main(String[] args) {
         AbstractApplicationContext context =
                 new  ClassPathXmlApplicationContext( "applicationContext.xml" );
         HelloWorld obj = (HelloWorld)context.getBean( "helloWorld" );
         obj.getMessage();
         context.registerShutdownHook();
 
     }

HelloWorld.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public  class  HelloWorld {
 
     private  String message;
 
     public  void  setMessage(String message) {
         this .message = message;
     }
 
     public  void  getMessage() {
         System.out.println( "Your Message : "  + message);
     }
 
     public  void  init() {
         System.out.println( "Bean is going through init." );
     }
 
     public  void  destroy() {
         System.out.println( "Bean will destroy now." );
     }
}

  



本文转自Work Hard Work Smart博客园博客,原文链接:http://www.cnblogs.com/linlf03/p/5177164.html,如需转载请自行联系原作者

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值