[b]Bean HelloBean.java[/b]
[b]Bean定义文件 bean-config.xml[/b]
可以使用setter injection, construction injection,此处使用setter注入
[b]BeanFactory[/b]
BeanFactory負責讀取Bean定义文件,管理对象的載入、生成,对象之間的關係維護,負責Bean的生命週期,對於簡單的應用程式來說,使用 BeanFactory就已經足夠,但是若要利用到Spring在框架上的一些功能以及進階的容器功能,則可以使用[u]ApplicationContext[/u]
package onlyfun.caterpillar;
public class HelloBean
{
private String helloWord;
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;
}
}
[b]Bean定义文件 bean-config.xml[/b]
可以使用setter injection, construction injection,此处使用setter注入
<?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!Justin!</value>
</property>
<property name="date">
<ref bean="dateBean"/>
</property>
<!-- 也可使用内部Bean注入,如下
<property name="date">
<bean id="dateBean" class="java.util.Date"/>
</property>
-->
</bean>
</beans>
[b]BeanFactory[/b]
BeanFactory負責讀取Bean定义文件,管理对象的載入、生成,对象之間的關係維護,負責Bean的生命週期,對於簡單的應用程式來說,使用 BeanFactory就已經足夠,但是若要利用到Spring在框架上的一些功能以及進階的容器功能,則可以使用[u]ApplicationContext[/u]
ApplicationContext context = new
FileSystemXmlApplicationContext("beans-config.xml");
HelloBean hello = (HelloBean) context.getBean("helloBean");