采用構造函數注入
Spring提供了四種自動裝配類型
例子源代碼如下
例子一個Java工程師從一個網站上買東本
一個普通的JavaBean
[java]
interface Engineer{
Object buyApple();
}
public class JavaEngineer implements Engineer{
private String name;
private Website ws;
public JavaEngineer(String name){
this
}
public void setWebsite(Website ws){
this
}
@Override
public String toString() {
// TODO Auto
return super
}
public Object buyApple(){
System
return ws
}
}
interface Engineer{
Object buyApple();
}
public class JavaEngineer implements Engineer{
private String name;
private Website ws;
public JavaEngineer(String name){
this
}
public void setWebsite(Website ws){
this
}
@Override
public String toString() {
// TODO Auto
return super
}
public Object buyApple(){
System
return ws
}
}
這個網站假設是淘寶網
[java]
interface Website{
Object buyApple();
}
public class TaobaoWebsite implements Website {
public TaobaoWebsite()
{
}
public Object buyApple()
{
System
return new Object();
}
}
interface Website{
Object buyApple();
}
public class TaobaoWebsite implements Website {
public TaobaoWebsite()
{
}
public Object buyApple()
{
System
return new Object();
}
}則采用自動裝配的ByName方式
[java]
<?xml version=
<beans
xmlns=
xmlns:xsi=
xmlns:p=
xsi:schemaLocation=
<!
<bean id=
<bean id=
<constructor
<!
</bean>
</beans>
<?xml version=
<beans
xmlns=
xmlns:xsi=
xmlns:p=
xsi:schemaLocation=
<!
<bean id=
<bean id=
<constructor
<!
</bean>
</beans>打印結果如下
[java]
工程師ppTest購買了一個蘋果
工程師ppTest購買了一個蘋果
有了第一個結果後
ByType的測試
修改配置文件如下
[html]
<!
<bean id=
<bean id=
<constructor
<!
</bean>
<!
<bean id=
<bean id=
<constructor
<!
</bean>其他的地方可以不用修改
Constructor自動裝配
[java]
public JavaEngineer(Website ws){
this
this
}
public JavaEngineer(Website ws){
this
this
}
再修改配置文件如下
[html]
<bean id=
<bean id=
<!
<!
</bean>
<bean id=
<bean id=
<!
<!
</bean>結果是一樣的
自動裝配autodetect
From:http://tw.wingwit.com/Article/program/Java/ky/201311/28710.html