熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java開源技術 >> 正文

Spring的三種注入方式都是什麼?如何選用?

2022-06-13   來源: Java開源技術 

接口注入(不推薦)

gettersetter方式注入(比較常用)

構造器注入(死的應用)

關於getter和setter方式的注入

autowire=&#;defualt&#;

autowire=byName

autowire=&#;bytype&#;

例如有如下兩個類需要注入
package orgjia;

public class Order {
private String orderNum;
@SuppressWarnings(&#;unused&#;)
private OrderItem orderitem;

public OrderItem getOrderitem() {
return orderitem;
}

public void setOrderitem(OrderItem orderitem) {
thisorderitem = orderitem;
}

public String getOrderNum() {
return orderNum;
}

public void setOrderNum(String orderNum) {
thisorderNum = orderNum;
}

}
package orgjia;

public class OrderItem {
private String orderdec;

public String getOrderdec() {
return orderdec;
}

public void setOrderdec(String orderdec) {
thisorderdec = orderdec;
}
}

getter&&setter方式第一種注入
<?xml version=&#;&#; encoding=&#;UTF&#;?>
<!DOCTYPE beans PUBLIC &#;//SPRING//DTD BEAN//EN&#; &#;;>

<beans>
<bean id=&#;orderItem&#;>
<property name=&#;orderdec&#; value=&#;item&#;></property>
</bean>
<bean id=&#;order&#; >
<!&#;&#;注入變量 名字必須與類中的名字一樣&#;&#;>
<property name=&#;orderNum&#; value=&#;order&#;></property>
<!&#;注入對象 名字為orderitem所屬的類的應用id為orderItem&#;>
<property name=&#;orderitem&#; ref=&#;orderItem&#;></property>

&#;></bean>

</beans>
getter&&setter方式第二種注入 byName
<?xml version=&#;&#; encoding=&#;UTF&#;?>
<!DOCTYPE beans PUBLIC &#;//SPRING//DTD BEAN//EN&#; &#;;>
<beans>
<!&#;此時的id就必須與Orderjava中所定義的OrderItem的對象名稱一樣了不然就會找不到&#;>
<bean id=&#;orderitem&#;>
<property name=&#;orderdec&#; value=&#;item&#;></property>
</bean>
<bean id=&#;order&#; autowire=&#;byName&#;>
<property name=&#;orderNum&#; value=&#;order&#;></property>
</bean>
</beans>
getter&&setter方式第三種注入byType
<?xml version=&#;&#; encoding=&#;UTF&#;?>
<!DOCTYPE beans PUBLIC &#;//SPRING//DTD BEAN//EN&#; &#;;>
<beans>
<!&#;按照byType注入則就與id沒有關系可以隨便定義id !!!但是不能出現多個此類的id&#;>
<bean id=&#;orderitdfadafaem&#;>
<property name=&#;orderdec&#; value=&#;item&#;></property>
</bean>
<bean id=&#;order&#; autowire=&#;byType&#;>
<property name=&#;orderNum&#; value=&#;order&#;></property>
</bean>
</beans>


From:http://tw.wingwit.com/Article/program/Java/ky/201404/30509.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.