Spring中bean有三种装配机制,分别是:
本文主要介绍第三种,自动化的装配bean
Spring的自动装配需要从两个角度来实现,或者说是两个操作:
组件扫描和自动装配组合发挥巨大威力,使的显示的配置降低到最少。
推荐不使用自动装配xml配置 , 而使用注解
autowire byName (按名称自动装配)
由于在手动配置xml过程中,常常发生字母缺漏和大小写等错误,而无法对其进行检查,使得开发效率降低。
采用自动装配将避免这些错误,并且使配置简单化。
测试:
<bean id="cat" class="com.lding.pojo.Cat">bean>
<bean id="dog" class="com.lding.pojo.Dog">bean>
<bean id="people" class="com.lding.pojo.People" autowire="byName">
<property name="name" value="冷丁">property>
bean>
注意这里的cat必须是cat 如果改成cat123就报错,cat和People类setCat后面这个Cat对应的小写cat对应,如果写成Cat也报错
autowire byType (按类型自动装配)
使用autowire byType首先需要保证:同一类型的对象,在spring容器中唯一。如果不唯一,会报不唯一的异常。
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="cat" class="com.lding.pojo.Cat">bean>
<bean id="dog" class="com.lding.pojo.Dog">bean>
<bean id="people" class="com.lding.pojo.People" autowire="byType">
<property name="name" value="冷丁">property>
bean>
beans>
建立三个类分别为dog,cat ,people,people拥有dog和cat
cat.java
public class Cat {
public void shout(){
System.out.println("喵喵喵");
}
}
dog.java
public class Dog {
public void shout(){
System.out.println("汪汪汪");
}
}
people.java
package com.lding.pojo;
public class People {
private Cat cat;
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 + '\'' +
'}';
}
}
beans.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="cat" class="com.lding.pojo.Cat">bean>
<bean id="dog" class="com.lding.pojo.Dog">bean>
<bean id="people" class="com.lding.pojo.People" autowire="byType">
<property name="name" value="冷丁">property>
bean>
beans>
test.java
public class MyTest {
@Test
public void test1(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
People people = context.getBean("people", People.class);
people.getDog().shout();
people.getCat().shout();
}
}