<?xml version="1.0" encoding="UTF-8"?>在定义档中,并没有指定helloBean的Date属性,而是透过自动绑定,由于autowire指定了byType,所以会根据helloBean的 Date属性所接受的型态,判断是否有类似的型态对象,并将之绑定至helloBean的Date属性上,如果byType无法完成绑定,则丢出 org.springrframework.beans.factory.UnsatisfiedDependencyExcpetion例外。
<!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"
autowire="byType">
<property name="helloWord">
<value>Hello!</value>
</property>
</bean>
</beans>
<?xml version="1.0" encoding="UTF-8"?>如果byName无法完成绑定,则属性维持未绑定状态。
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="date" class="java.util.Date"/>
<bean id="helloBean"
class="onlyfun.caterpillar.HelloBean"
autowire="byName">
<property name="helloWord">
<value>Hello!</value>
</property>
</bean>
</beans>
package onlyfun.caterpillar;您可以如下定义beans-config.xml:
import java.util.Date;
public class HelloBean {
private String helloWord;
private Date date;
public HelloBean() {
}
public HelloBean(Date date) {
this.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"?>由于autowire设定为constructor,在建立绑定关系时,Spring容器会试图比对容器中的Bean及相关的建构方法,在型态上是否有符 合,如果有的话,则选用该建构方法来建立Bean实例,例如上例中,HelloBean的带参数建构方法与date这个Bean的型态相符,于是选用该建 构方法来建构实例,并将date这个Bean注入给它,如果无法完成绑定,则丢出 org.springframework.beans.factory.UnsatisfiedDependencyException例外。
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="date" class="java.util.Date"/>
<bean id="helloBean"
class="onlyfun.caterpillar.HelloBean"
autowire="constructor">
<property name="helloWord">
<value>Hello!</value>
</property>
</bean>
</beans>
<?xml version="1.0" encoding="UTF-8"?>使用autodetect时,会尝试使用constructor,然后使用byType,哪一个先符合就先用。
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="date" class="java.util.Date"/>
<bean id="helloBean"
class="onlyfun.caterpillar.HelloBean"
autowire="autodetect">
<property name="helloWord">
<value>Hello!</value>
</property>
</bean>
</beans>
<?xml version="1.0" encoding="UTF-8"?>如果相依检查发现有未完成的依赖关系,则运行时会丢出org.springframework.beans.factory.UnsatisfiedDependencyException。
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="date" class="java.util.Date"/>
<bean id="helloBean"
class="onlyfun.caterpillar.HelloBean"
autowire="autodetect"
dependency-check="all">
<property name="helloWord">
<value>Hello!</value>
</property>
</bean>
</beans>