Spring-Bean的初始化(init方法和实现org.springframework.beans.factory.InitializingBean接口)

来源:互联网 发布:小姐威客网络兼职 编辑:程序博客网 时间:2024/04/28 23:25

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""http://www.springframework.org/dtd/spring-beans.dtd"><beans>    <!--定义一个Bean-->    <bean id="HelloWorld" class="com.gc.action.HelloWorld" 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;//该变量用来存储日期@Overridepublic void afterPropertiesSet() {// TODO Auto-generated method stubthis.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""http://www.springframework.org/dtd/spring-beans.dtd"><beans>    <!--定义一个Bean-->    <bean id="HelloWorld" class="com.gc.action.HelloWorld" >    <!--将其变量msg通过依赖注入-->         </bean>    </beans>


测试程序不需要改



输出:

HelloWorld Mon Mar 19 16:33:41 CST 2012


第一种方法好,因为第一种方法没有把代码耦合于spring





原创粉丝点击