在学习spring IOC的过程中,接触到@Autowired注解,资料上都是说默认是按照Bytype类型实现自动注入,但我的实际操作却发现是:先使用ByName,如果失败,再使用ByType。贴代码,求指点:
Student类:
@Component
public class Student {
@Value("12")
int age;
@Value("lisa")
String name;
@Autowired
School school;
public Student(){}
public Student(int age, String name, School school) {
this.age = age;
this.name = name;
this.school = school;
}
@Override
public String toString() {
return "Student{" +
"age=" + age +
", name='" + name + '\'' +
", school=" + school +
'}';
}
}
School类:
public class School {
String name;
String address;
public School() {
}
public School(String name, String address) {
this.name = name;
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
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 http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!--配置注解扫描器,base-package表示注解所在的包,目的是告诉spring框架去扫描指定包的注解-->
<context:component-scan base-package="com.aipande.bao1"/>
<bean id="school" class="com.aipande.bao1.School">
<property name="name" value="武汉大学21"/>
</bean>
<bean id="school03" class="com.aipande.bao1.School">
<property name="name" value="武汉大学21"/>
</bean>
<bean id="school02" class="com.aipande.bao1.School">
<property name="name" value="武汉大学"/>
</bean>
</beans>
测试类:
public class AppTest01 {
public static void main(String[] args) {
/*
* 创建spring容器对象
* spring框架在加载xml文件并创建spring容器对象的同时,
* 就会将xml文件中配置的bean对象(作用域为singleton)一同创建,并将这些对象放置在spring容器中。
* */
String config = "applicationContext.xml";
ApplicationContext ctx = new ClassPathXmlApplicationContext(config);
//使用getBean()方法获取bean对象
Student stu = (Student) ctx.getBean("student");
System.out.println(stu);
}
}
结果输出:
Student{age=12, name='lisa', school=School{name='武汉大学21', address='null'}}
问题:
如果按照Bytype方式获取bean对象,那上面就应该报错啊,因为sprig容器中存在多个同源bean对象,但是没有报错,说明是按照byName的方式注入。后来我将xml文件中id为school的bean对象删除,就出现了错误提示,说明此时是按照byType的方式注入。因此我有上面的疑问,求解