DI exists in two major variants: Constructor-based dependency injection and Setter-based dependency injection.
bean的依赖注入
set方法注入
在类中写好属性名,为该属性提供set方法(必须)
<bean id="bookService" class="service.BookServiceImpl" scope="singleton" >
<property name="bookDao1" ref="bookDao"/>
<property name="connectionNum" value="10"/>
<property name="databaseName" value="mysql"/>
</bean>
通过构造bean的方法进行注入
public BookServiceImpl(TestDao testDao, int i, String s){
}
<bean id="bookService" class="service.BookServiceImpl" scope="singleton">
<constructor-arg index="0" ref="testDao"/>
<constructor-arg index="1" value="2353"/>
<constructor-arg index="2" value="南京"/>
</bean>
类中只有有参构造,在xml中就必须要提供
<constructor-arg/>
,用于实例化bean,Spring默认使用无参构造创建bean
有多个构造方法时,执行哪个方法,取决于
<constructor-arg>
数量,被执行的构造方法的参数个数和写的
<constructor-arg>
的个数相同
// 对于注解形式被@Component标注的bean
// 实例化bean时
// 构造器的权限修饰符无效,因为使用的反射
// 只有一个构造器时,就用那个构造器实例化对象,且可通过传递参数的方式进行DI
// 有多个构造器时,且没有使用@Autowired指定,就去找无参的,如果没有就会报错
// As of Spring Framework 4.3, an @Autowired annotation on such a constructor is no longer necessary
// if the target bean defines only one constructor to begin with.
// However, if several constructors are available and there is no primary/default constructor, at least one
// of the constructors must be annotated with @Autowired in order to instruct the container which one to use.
public class MovieRecommender {
private final CustomerPreferenceDao customerPreferenceDao;
@Autowired
public MovieRecommender(CustomerPreferenceDao customerPreferenceDao) {
this.customerPreferenceDao = customerPreferenceDao;
}
// ...
}
注入集合数据类型
public class BookDaoImpl implements BookDao {
private int[] array1;
private List<String> list1;
private Set<String> set1;
private Map<String,String> map1;
private Properties properties1;
// set方法
public void save(){
System.out.println("数组:" + Arrays.toString(array1));
System.out.println("List:" + list1);
System.out.println("Set:" + set1);
System.out.println("Map:" + map1);
System.out.println("Properties:" + properties1);
}
}
<bean id="bookDao" class="dao.BookDaoImpl">
<property name="array1">// 数组:[10, 11, 12]
<array>
<value>10</value>
<value>11</value>
<value>12</value>
</array>
</property>
<property name="list1">// List:["fjk", fjkl, "fjk"]
<list>
<value>"fjk"</value>
<value>fjkl</value>
<value>"fjk"</value>
</list>
</property>
<property name="set1">// Set:[jdjks, "vd", jds]
<set>
<value>jdjks</value>
<value>"vd"</value>
<value>jds</value>
</set>
</property>
<property name="map1">// Map:{country=china, province=henan, city=12}
<map>
<entry key="country" value="china"/>
<entry key="province" value="henan"/>
<entry key="city" value="12"/>
</map>
</property>
<property name="properties1">// Properties:{country="china", province=12, city=kaifeng}
<props>
<prop key="country">"china"</prop>
<prop key="province">12</prop>
<prop key="city">kaifeng</prop>
</props>
</property>
</bean>
版权声明:本文为qq_53318060原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。