1.首先需要在bean.xml中进行配置
xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
<context:annotation-config/>
<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="cat1" class="com.superman.pojo.Cat"/>
<bean id="cat2" class="com.superman.pojo.Cat"/>
<bean id="dog" class="com.superman.pojo.Dog"/>
<bean id="people" class="com.superman.pojo.People"/>
</beans>
package com.superman.pojo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import javax.annotation.Resource;
/**
* @ClassName com.superman.pojo.People
* @Description TODO
* @Author 披风超人
* @Date 2020-3-21 16:19
* @Version 1.0
**/
public class People {
private String name;
@Autowired
@Qualifier(value = "cat1")
private Cat cat;
@Resource
private Dog dog;
public String getName() {
return name;
}
public void setName(String name) {
this.name = 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;
}
}
2.对于使用@Autowird的理解
使用这种注解方法需要bean中的class是唯一的
如果不是唯一的,但是存在一个class的id为对应class的小写,也可以匹配
如果class不唯一,id也没有对应的,则会报错
由此可以发现,这样的注解方式是先bytype然后通过byname去查找的
如果class不唯一且没有对应的id
解决办法就是使用@Qualifier(value=“对应的自定义的id”)
@Qualifier不能单独使用
3.使用@Resource
@Resource如有指定的name属性,先按该属性进行byName方式查找装配;
其次再进行默认的byName方式进行装配;
如果以上都不成功,则按byType的方式自动装配。
都不成功,则报异常。
@Autowired与@Resource异同:
@Autowired与@Resource都可以用来装配bean。都可以写在字段上,或写在setter方法上。
@Autowired默认按类型装配(属于spring规范),默认情况下必须要求依赖对象必须存在,如果要允许null 值,可以设置它的required属性为false,如:@Autowired(required=false) ,如果我们想使用名称装配可以结合@Qualifier注解进行使用
@Resource(属于J2EE复返),默认按照名称进行装配,名称可以通过name属性进行指定。如果没有指定name属性,当注解写在字段上时,默认取字段名进行按照名称查找,如果注解写在setter方法上默认取属性名进行装配。 当找不到与名称匹配的bean时才按照类型进行装配。但是需要注意的是,如果name属性一旦指定,就只会按照名称进行装配。
它们的作用相同都是用注解方式注入对象,但执行顺序不同。@Autowired先byType,@Resource先byName。