jdk1.5开始支持注解,spring2.5开始全面支持注解。
准备工作: 利用注解的方式注入属性。
在spring配置文件中引入context文件头
开启注解支持!
<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>
直接在属性上使用即可,也可以在set方法上使用。
使用Autowired后,可以不用编写set方法!
People类
package com.codeyancy.pojo;
import org.springframework.beans.factory.annotation.Autowired;
public class People {
@Autowired
private Cat cat;
@Autowired
private Dog dog;
private String name;
public Cat getCat() {
return cat;
}
public void setCat(Cat cat) {
this.cat = cat;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "People{" +
"cat=" + cat +
", dog=" + dog +
", name='" + name + '\'' +
'}';
}
}
2.配置文件内容(beans.xml)
<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">
<bean id="cat" class="com.codeyancy.pojo.Cat"/>
<bean id="dog" class="com.codeyancy.pojo.Dog"/>
<bean id="people" class="com.codeyancy.pojo.People" />
<context:annotation-config/>
beans>
3.测试,成功输出结果!
@Autowired(required=false) 说明: false,对象可以为null;true,对象必须存对象,不能为null。
//如果允许对象为null,设置required = false,默认为true
@Autowired(required = false)
private Cat cat;
如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解【@Autowired】完成的时候、可以使用@Qualifier(value=“xx”)去配合@Autowired的使用,指定一个唯一的bean对象注入
public class People {
@Autowired
@Qualifier(value = "cat111")
private Cat cat;
@Autowired
@Qualifier(value = "dog222")
private Dog dog;
private String name;
public class People {
@Resource(name="cat2")
private Cat cat;
@Resource
private Dog dog;
private String name;
beans.xml
<bean id="cat1" class="com.codeyancy.pojo.Cat"/>
<bean id="cat2" class="com.codeyancy.pojo.Cat"/>
<bean id="dog" class="com.codeyancy.pojo.Dog"/>
<bean id="people" class="com.codeyancy.pojo.People" />
测试:结果OK
配置文件2:beans.xml , 删掉cat2
<bean id="cat2" class="com.codeyancy.pojo.Cat"/>
<bean id="dog" class="com.codeyancy.pojo.Dog"/>
<bean id="people" class="com.codeyancy.pojo.People" />
实体类上只保留注解
public class People {
@Resource
private Cat cat;
@Resource
private Dog dog;
private String name;
测试:结果OK
结论:先进行byName查找,失败;再进行byType查找,成功。
@Autowired与@Resource异同:
它们的作用相同都是用注解方式注入对象,但执行顺序不同。@Autowired先byType,@Resource先 byName。