package onlyfun.caterpillar;
import java.util.Date;
public class HelloBean {
private String helloWord;
private Date date;
public void setHelloWord(String helloWord) {
this.helloWord = helloWord;
}
public String getHelloWord() {
return helloWord;
}
public void setDate(Date date) {
this.date = date;
}
public Date getDate() {
return 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 id="dateBean" class="java.util.Date"/>
<bean id="helloBean" class="onlyfun.caterpillar.HelloBean">
<property name="helloWord">
<value>Hello!</value>
</property>
<property name="date">
<ref bean="dateBean"/>
</property>
</bean>
</beans>
package onlyfun.caterpillar;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class SpringDemo {
public static void main(String[] args) {
ApplicationContext context =
new FileSystemXmlApplicationContext("beans-config.xml");
HelloBean hello =
(HelloBean) context.getBean("helloBean");
System.out.print(hello.getHelloWord());
System.out.print(" It's ");
System.out.print(hello.getDate());
System.out.println(".");
}
}
Hello! It's Sat Oct 22 15:36:48 GMT+08:00 2005.事实上,您也可以用内部Bean的方式来注入依赖关系,例如beans-config.xml可以改为以下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="helloBean" class="onlyfun.caterpillar.HelloBean">
<property name="helloWord">
<value>Hello!</value>
</property>
<property name="date">
<bean id="dateBean" class="java.util.Date"/>
</property>
</bean>
</beans>