741
技術社區[雲棲]
Spring-Bean的初始化(init方法和實現org.springframework.beans.factory.InitializingBean接口)
init()方法
在BEAN中增加一個方法inti(),用來完成初始化工作(去掉構造函數)
然後修改配置文檔config.xml,指定Bean中要初始化的方法,
最後編寫測試程序
Bean
package com.gc.action; import java.util.Date; public class HelloWorld { private String msg=null;//該變量用來存儲字符串 private Date date=null;//該變量用來存儲日期 // public HelloWorld(String msg) // { // this.msg=msg; // } // // public HelloWorld()//這個必須寫,否則不能轉到上麵的那個 // { // this.msg=msg; // } public void init(){ this.msg="HelloWorld"; this.date=new Date(); } //設定變量msg的set方法 public void setMsg(String msg) { this.msg=msg; } //獲取變量msg的get方法 public String getMsg() { return this.msg; } public Date getDate() { return this.date; } public void setDate(Date date) { this.date = date; } }
配置文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "https://www.springframework.org/dtd/spring-beans.dtd"> <beans> <!--定義一個Bean--> <bean init-method="init"> <!--將其變量msg通過依賴注入--> </bean> </beans>
測試程序
package com.gc.test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; import com.gc.action.HelloWorld; public class TestHelloWorld { public static void main(String[] args) { //通過ApplicationContext來獲取Spring文件的配置 ApplicationContext actx=new FileSystemXmlApplicationContext("config.xml"); //通過Bean的id來獲取Bean HelloWorld helloworld=(HelloWorld)actx.getBean("HelloWorld"); //打印輸出 System.out.println(helloworld.getMsg()+" "+helloworld.getDate()); } }
方法2:實現org.springframework.beans.factory.InitializingBean接口
1.首先讓HelloWorld.java實現InitializingBena接口,增加一個方法afterPropertiesSet()用來完成初始化工作
2.然後修改配置文檔config.xml
3.最後編寫測試程序TestHelloWorld.java
package com.gc.action; import org.springframework.beans.factory.InitializingBean; import java.util.Date; public class HelloWorld implements InitializingBean{ private String msg=null;//該變量用來存儲字符串 private Date date=null;//該變量用來存儲日期 @Override public void afterPropertiesSet() { // TODO Auto-generated method stub this.msg="HelloWorld"; this.date=new Date(); } // public HelloWorld(String msg) // { // this.msg=msg; // } // // public HelloWorld()//這個必須寫,否則不能轉到上麵的那個 // { // this.msg=msg; // } // public void init(){ // // } //設定變量msg的set方法 public void setMsg(String msg) { this.msg=msg; } //獲取變量msg的get方法 public String getMsg() { return this.msg; } public Date getDate() { return this.date; } public void setDate(Date date) { this.date = date; } }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "https://www.springframework.org/dtd/spring-beans.dtd"> <beans> <!--定義一個Bean--> <bean > <!--將其變量msg通過依賴注入--> </bean> </beans>
測試程序不需要改
輸出:
HelloWorld Mon Mar 19 16:33:41 CST 2012
第一種方法好,因為第一種方法沒有把代碼耦合於spring
最後更新:2017-04-02 22:16:38