java

位置:IT落伍者 >> java >> 浏览文章

Spring的三种注入方式都是什么?如何选用?


发布日期:2021年10月28日
 
Spring的三种注入方式都是什么?如何选用?

接口注入(不推荐)

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>

上一篇:如何优化Hibernate?

下一篇:算法面试题 找出所有的数字组合 挑战一下吧!