Spring Study-lesson08-使用注解实现自动加载-03-16
1、配置XML 注解支持: <context:annotation-config/>
<?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-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:annotation-config/>
<bean id="cat" class="com.feijian.pojo.Cat"/>
<bean id="dog" class="com.feijian.pojo.Dog"/>
<bean id="people" class="com.feijian.pojo.People" >
</beans>
第二步,在类中加入@autowired 注解 ,加完后其实set方法都可以不需要加
package com.feijian.pojo;
import org.springframework.beans.factory.annotation.Autowired;
public class People {
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 Cat getCat() {
return cat;
}
@Override
public String toString() {
return "People{" +
"name='" + name + '\'' +
", dog=" + dog +
", cat=" + cat +
'}';
}
}
第三:注解@Autowired 和另外一个注解 @Qualifier 配合使用,指定一个唯一的bean 这个是最常用的,必须要求这个对象存在
@Autowired
@Qualifier(value = "dog1")
private Dog dog;
@Autowired
@Qualifier(value = "cat")
private Cat cat;
第四:还有另外一种注解 @Resource ---- 可以不需要注解@Autowired 和另外一个注解 @Qualifier