spring 注解实现自动装配
1、导入约束
2、配置注解支持
<?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/> </beans>
1、pojo
person.java
package com.wt.pojo; import org.springframework.beans.factory.annotation.Autowired; public class Person { private String name; @Autowired private Dog dog; @Autowired private Cat cat; public String getName() { return name; } public void setName(String name) { this.name = name; } public Dog getDog() { return dog; } public void setDog(Dog dog) { this.dog = dog; } public Cat getCat() { return cat; } public void setCat(Cat cat) { this.cat = cat; } }
2、xml配置文件
<?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="cat" class="com.wt.pojo.Cat"/> <bean id="dog" class="com.wt.pojo.Dog"/> <bean id="person" class="com.wt.pojo.Person" name="per"> <property name="name" value="win"/> </bean> </beans>
如果@Autowrited自动装配的环境比较复杂,自动装配无法通过一个注解 @Autowrited 完成的时候
使用@Qualifier(value = "xx")配合使用