使用注解注入属性
@Autowired与@Qualifier
1.
1.
1. 将@Autowired加在实体类的属性上面,可以自动通过属性名或属性类型来自动装配;
2.
2.
2. 如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解@Autowired完成的时候,我们可以使用@Qualifier(value = “xxx”)去配置@Autowired的使用,指定一个唯一的bean对象注入;
3.
3.
3. 使用@Autowired后就不需要set方法了。
package com.tl.pojo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
/**
* @author tl
*/
public class People {
private String name;
@Autowired
@Qualifier(value = "dog22")
private Dog dog;
@Autowired
private Cat cat;
public People() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Dog getDog() {
return dog;
}
public Cat getCat() {
return cat;
}
}
配置
<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<bean id="cat11" class="com.tl.pojo.Cat"/>
<bean id="dog22" class="com.tl.pojo.Dog"/>
<bean id="dog23" class="com.tl.pojo.Dog"/>
<bean id="people" class="com.tl.pojo.People">
<property name="name" value="tl"/>
<!-- <property name="cat" ref="cat"/>-->
<!-- <property name="dog" ref="dog"/>-->
</bean>
</beans>