样式类:
package com.yyf.pojo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import javax.annotation.Resource;
public class People {
@Resource(name="dog11")
// @Autowired 自动分配 通过byType实现
// @Qualifier(value="dog111") == @Resource(name="dog11") resource用byName实现
private Dog dog;
// @Autowired
// @Qualifier(value="cat111") //当类有多个bean对象时,用Qualifier 指定bean
@Resource(name="cat111")
private Cat cat;
private String name;
public People() {
}
public People(Dog dog, Cat cat, String name) {
this.dog = dog;
this.cat = cat;
this.name = name;
}
public Dog getDog() {
return dog;
}
public Cat getCat() {
return cat;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "People{" +
"dog=" + dog +
", cat=" + cat +
", name='" + name + '\'' +
'}';
}
}
spring 配置文件
byName:会自动寻找容器上下文和自己对象set后面值相对应的beanID 必须保证beanId唯一
byType:当我们要往一个bean的某个属性里注入另外一个bean,我们会使用<property> + <ref/>标签的形式。但是对于大型项目,假设有一个bean A被多个bean引用注入,如果A的id因为某种原因修改了,那么所有引用了A的bean的<ref/>标签内容都得修改,这时候如果使用autowire="byType",那么引用了A的bean就完全不用修改了。
<bean id="people" class="com.yyf.pojo.People" autowire="byName"/>
<bean id="people" class="com.yyf.pojo.People" autowire="byType">
<property name="name" value="杨小法"/>
<?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"
xmlns:aop="http://www.springframework.org/schema/aop"
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
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/context/spring-aop.xsd">
<!--开启注解的支持-->
<context:annotation-config/>
<bean id="cat" class="com.yyf.pojo.Cat"/>
<bean id="cat111" class="com.yyf.pojo.Cat"/>
<bean id="dog111" class="com.yyf.pojo.Dog"/>
<bean id="dog11" class="com.yyf.pojo.Dog"/>
<bean id="people" class="com.yyf.pojo.People"/>
</beans>
<!-- byName会自动寻找容器上下文和自己对象set后面值相对应的beanID 必须保证beanid唯一-->
<!-- byType会自动寻找容器上下文和自己对象set后面类型相对应的beanID 但使用byType时,一个类不能有多个bean 不声明id也行 与类类型所对应的类型就行
必须保证class唯一-->
<!-- <bean id="people" class="com.yyf.pojo.People" autowire="byName"/>-->
<!-- <bean id="people" class="com.yyf.pojo.People" autowire="byType">-->
<!-- <property name="name" value="杨小法"/>-->
<!-- </bean>-->