spring的2种注入方式

1,Set注入    2,构造注入

Set方法注入:

设置的是property属性。且VO类中,必须带有get/set方法才可以完成注入

<?xml version="1.0" encoding="UTF-8"?> 
<beans
  xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:p="http://www.springframework.org/schema/p"
  xsi:schemaLocation="http://www.springframework.org/schema/beans  
  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> 
  
  <bean id="car" class="org.spring01.Car"> 
    <constructor-arg value="奔驰"></constructor-arg> 
    <constructor-arg type="java.lang.String"> 
      <value>土豪金</value> 
    </constructor-arg> 
    <constructor-arg value="高级轿车"></constructor-arg> 
  </bean> 
    
  <bean id="person" class="org.spring01.Person"> 
    <property name="name" value="张三"></property> 
    <property name="age" value="11"></property> 
    <property name="car" ref="car"></property> 
  </bean> 
</beans>

测试结果:

Person [name=张三, age=11, car=Car [name=奔驰, color=土豪金, clas=高级轿车]]

 

 

构造方法注入:

设置的是constructor-arg属性。且VO类中,必须带有有参构造才可以完成注入

<?xml version="1.0" encoding="UTF-8"?> 
<beans
  xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:p="http://www.springframework.org/schema/p"
  xsi:schemaLocation="http://www.springframework.org/schema/beans  
  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> 
  
  <bean id="car" class="org.spring02.Car"> 
    <constructor-arg value="大众"></constructor-arg> 
    <constructor-arg type="java.lang.String"> 
      <value>白色</value> 
    </constructor-arg> 
    <constructor-arg value="中级轿车"></constructor-arg> 
  </bean> 
    
    
  <bean id="person" class="org.spring02.Person"> 
    <constructor-arg index="0" value="李四"></constructor-arg> 
    <constructor-arg index="1" value="23"></constructor-arg> 
    <constructor-arg index="2" ref="car"></constructor-arg> 
  </bean> 
</beans>

测试结果:

Person [name=李四, age=23, car=Car [name=大众, color=白色, clas=中级轿车]]

 

set方法和构造方法都可以设值成功, 实际开发中最常用到的是set方法设值。但这两种依赖注入的方式并没有绝对的好坏,只是使用的场合不同。

使用构造注入可以在构建对象的同时完成依赖关系到的建立,所以如果要建立的对象的关系很多,使用构造注入会在构造方法上留下很多参数,可读性极差,所以当对象的关系比较多的时候采用set方法注入。

使用set方法注入是通过类的setter方法完成依赖关系的设置的,所以不能保证相关的数据在执行时不被更改设定。所以如果想使一些数据变为只读或者私有,就要采用构造注入了。

建议采用以set注入为主,构造注入为辅的注入策略。对于依赖关系无须变化的注入,尽量采用构造注入;而其他的依赖关系的注入,则考虑采用set注入。

 

参考来源:

https://www.jb51.net/article/113833.htm

 

posted @ 2020-07-15 15:23  林被熊烟岛  阅读(362)  评论(0编辑  收藏  举报