一、首先在spring配置文件加上相应的配置
<?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 http://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/>
</beans>
比起一般的spring配置,主要增加了以下几行:
<beans
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
</beans>
二、在需要装配的类中添加注释
这里用到了三个类,Address、Name和People,其中Address和Name是People中的属性类型。
- Autowired注释是通过ByType和ByName方式进行自动装配的。
- ByName的优先级比ByType高,即有多个同类的bean时,程序会使用和目标类的属性同名的bean。
- 多个同类的bean时,但没有和目标类的属性同名的bean时,程序会报错。
- 使用Qualifier时,配置中必须要有指定名字的bean。
package cn.scut.pojo;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
@Data
public class People {
@Autowired //自动装配该属性
@Qualifier(value = "name")//指定注入的bean对象
private Name name;
@Autowired
private Address address;
}
package cn.scut.pojo;
import lombok.Data;
@Data
public class Address {
private String address;
}
package cn.scut.pojo;
import lombok.Data;
@Data
public class Name {
private String name;
}
三、配置beans
<?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 http://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="people" class="cn.scut.pojo.People"/>
<bean id="name" class="cn.scut.pojo.Name">
<property name="name" value="小明"/>
</bean>
<bean id="address" class="cn.scut.pojo.Address">
<property name="address" value="文明路"/>
</bean>
</beans>