首先在名称为HelloWorld的Bean中增加一个Date类型的私有变量
然后改写Spring的配置文档config.xml,添加一个id为date的Bean,并在原来的id为HelloWorld的Bean中参考配置文档中定义的id为date的Bean
最后修改测试程序TestHelloWorld.java
一定要注意构造函数!
helloworld.java
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; } //设定变量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; } }
不写构造函数的话,JVM虚拟机内部会默认去找原先的那个没有参数的构造函数,从而导致我的程序出错!
<?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通过依赖注入--> <property name="msg"> <value>english zhuzhengke</value> </property> <property name="date"> <ref bean="date"/> </property> </bean> <bean id="date" class="java.util.Date"/> </beans>
TestHelloWorld.java
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()); } }
输出:
english zhuzhengkeMon Mar 19 15:10:02 CST 2012
另外一种定义BEAN属性的方法:
<?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通过依赖注入--> <property name="msg"> <value>english zhuzhengke</value> </property> <property name="date"> <bean id="date" class="java.util.Date"/> </property> </bean> </beans>
输出:
english zhuzhengkeMon Mar 19 15:10:02 CST 2012