當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring Bean InitializingBean和DisposableBean实例
生活随笔
收集整理的這篇文章主要介紹了
Spring Bean InitializingBean和DisposableBean实例
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在Spring中,InitializingBean和DisposableBean是兩個標記接口,為Spring執行時bean的初始化和銷毀某些行為時的有用方法。 對于Bean實現 InitializingBean,它將運行 afterPropertiesSet()在所有的 bean 屬性被設置之后。 對于?Bean?實現了DisposableBean,它將運行?destroy()在?Spring?容器釋放該?bean?之后。
不建議使用InitializingBean和DisposableBean的接口,因為它將你的代碼緊耦合到 Spring 代碼中。?一個更好的做法應該是在bean的配置文件屬性指定init-method和destroy-method。 下載代碼 –?http://pan.baidu.com/s/1nu3cEXN
示例
下面是一個例子,向您展示如何使用 InitializingBean 和 DisposableBean。一個 CustomerService?bean來實現 InitializingBean和DisposableBean 接口,并有一個消息(message)屬性。 package com.yiibai.customer.services;import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean;public class CustomerService implements InitializingBean, DisposableBean {String message;public String getMessage() {return message;}public void setMessage(String message) {this.message = message;}public void afterPropertiesSet() throws Exception {System.out.println("Init method after properties are set : " + message);}public void destroy() throws Exception {System.out.println("Spring Container is destroy! Customer clean up");}}File : applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd"><bean id="customerService" class="com.yiibai.customer.services.CustomerService"><property name="message" value="I'm property message" /></bean></beans>執行它
package com.yiibai.common;import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;import com.yiibai.customer.services.CustomerService;public class App {public static void main( String[] args ){ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"applicationContext.xml"});CustomerService cust = (CustomerService)context.getBean("customerService");System.out.println(cust);context.close();} } 該ConfigurableApplicationContext.close()將關閉該應用程序的上下文,釋放所有資源,并銷毀所有緩存的單例bean。它是只用于?destroy()?方的演示目的。輸出結果
Init method after properties are set : I'm property message com.yiibai.customer.services.CustomerService@4090c06f Spring Container is destroy! Customer clean up afterPropertiesSet()方法被調用在 message 屬性設置后,而 destroy()方法是在調用 context.close()之后; 建議:不建議使用InitializingBean和DisposableBean的接口,因為它將你的代碼緊耦合到 Spring 代碼中。?一個更好的做法應該是在bean的配置文件屬性指定init-method和destroy-method。 下載代碼 –?http://pan.baidu.com/s/1nu3cEXN
總結
以上是生活随笔為你收集整理的Spring Bean InitializingBean和DisposableBean实例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 牙龈发炎怎么办刷牙容易出血(牙龈发炎怎么
- 下一篇: wordclock是什么意思(wordc