Spring学习--xml 中 Bean 的自动装配

时间:2022-03-30 20:02:45

简介

    Spring IOC 容器可以自动装配 Bean。 只要在 <bean> 的 autowire 属性里指定自动装配的模式。

  1. byName(根据名称自动装配):必须将目标 Bean 的名称和当前 Bean 指定的类中的 setter 名称相匹配。
  2. byType(根据类型自动装配):必须目标 Bean 的类型和当前 Bean 的类型相匹配。
  3. Constructor(构造函数自动装配):比较复杂,不推荐使用。

名称自动装配

 <?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="car" class="com.itdjx.spring.beans.aotuwire.Car" p:brand="Baoma" p:price="230000" />
<bean id="address" class="com.itdjx.spring.beans.aotuwire.Address" p:city="Dalian" p:street="ShaHeKou"/>
<bean id="person" class="com.itdjx.spring.beans.aotuwire.Person" p:name="Tom" autowire="byName"/> </beans>
 package com.itdjx.spring.beans.aotuwire;

 /**
* @author Wáng Chéng Dá
* @create 2017-03-01 10:59
*/
public class Car { private String brand;
private double price; public String getBrand() {
return brand;
} public void setBrand(String brand) {
this.brand = brand;
} public double getPrice() {
return price;
} public void setPrice(double price) {
this.price = price;
} @Override
public String toString() {
return "Car{" +
"brand='" + brand + '\'' +
", price=" + price +
'}';
}
}
 package com.itdjx.spring.beans.aotuwire;

 /**
* @author Wáng Chéng Dá
* @create 2017-03-01 10:59
*/
public class Address { private String city; private String street; public String getCity() {
return city;
} public void setCity(String city) {
this.city = city;
} public String getStreet() {
return street;
} public void setStreet(String street) {
this.street = street;
} @Override
public String toString() {
return "Address{" +
"city='" + city + '\'' +
", street='" + street + '\'' +
'}';
}
}
 package com.itdjx.spring.beans.aotuwire;

 /**
* @author Wáng Chéng Dá
* @create 2017-03-01 10:59
*/
public class Person { private String name; private Address address; private Car car; public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Address getAddress() {
return address;
} public void setAddress(Address address) {
this.address = address;
} public Car getCar() {
return car;
} public void setCar(Car car) {
this.car = car;
} @Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", address=" + address +
", car=" + car +
'}';
}
}
 package com.itdjx.spring.beans.aotuwire;

 import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; /**
* @author Wáng Chéng Dá
* @create 2017-03-01 11:05
*/
public class Main { public static void main(String[] args) {
ApplicationContext app = new ClassPathXmlApplicationContext("beans-aotuwire.xml");
Person person = (Person) app.getBean("person");
System.out.println(person);
}
}

控制台输出:

Person{name='Tom', address=Address{city='Dalian', street='ShaHeKou'}, car=Car{brand='Baoma', price=230000.0}}

若修改配置文件中的 address 为 address1 :

 <?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="car" class="com.itdjx.spring.beans.aotuwire.Car" p:brand="Baoma" p:price="230000" />
<bean id="address1" class="com.itdjx.spring.beans.aotuwire.Address" p:city="Dalian" p:street="ShaHeKou"/>
<bean id="person" class="com.itdjx.spring.beans.aotuwire.Person" p:name="Tom" autowire="byName"/> </beans>

控制台输出:

Person{name='Tom', address=null, car=Car{brand='Baoma', price=230000.0}}

出现这种状况说明自动装配没有匹配到 address 对象。id="address" 与 Person 中的 setAdress() 方法匹配。

 类型自动装配

 <?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="car" class="com.itdjx.spring.beans.aotuwire.Car" p:brand="Baoma" p:price="230000" />
<bean id="address1" class="com.itdjx.spring.beans.aotuwire.Address" p:city="Dalian" p:street="ShaHeKou"/>
<bean id="person" class="com.itdjx.spring.beans.aotuwire.Person" p:name="Tom" autowire="byType"/> </beans>

控制台输出:

Person{name='Tom', address=Address{city='Dalian', street='ShaHeKou'}, car=Car{brand='Baoma', price=230000.0}}

若是多定义几个相同的类 , 程序会出现异常。

 <?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="car" class="com.itdjx.spring.beans.aotuwire.Car" p:brand="Baoma" p:price="230000" />
<bean id="address1" class="com.itdjx.spring.beans.aotuwire.Address" p:city="Dalian" p:street="ShaHeKou"/>
<bean id="address" class="com.itdjx.spring.beans.aotuwire.Address" p:city="ShenYang" p:street="Dadong"/>
<bean id="person" class="com.itdjx.spring.beans.aotuwire.Person" p:name="Tom" autowire="byType"/> </beans>

控制台输出:

警告: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'person' defined in class path resource [beans-aotuwire.xml]: Unsatisfied dependency expressed through bean property 'address'; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.itdjx.spring.beans.aotuwire.Address' available: expected single matching bean but found 2: address1,address
Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'person' defined in class path resource [beans-aotuwire.xml]: Unsatisfied dependency expressed through bean property 'address'; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.itdjx.spring.beans.aotuwire.Address' available: expected single matching bean but found 2: address1,address
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireByType(AbstractAutowireCapableBeanFactory.java:1357)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1249)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.itdjx.spring.beans.aotuwire.Main.main(Main.java:13)
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.itdjx.spring.beans.aotuwire.Address' available: expected single matching bean but found 2: address1,address
at org.springframework.beans.factory.config.DependencyDescriptor.resolveNotUnique(DependencyDescriptor.java:173)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1116)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireByType(AbstractAutowireCapableBeanFactory.java:1342)
... 13 more

xml 中 Bean 自动装配的缺点

  1. 在 Bean 配置文件里设置 autowire 属性进行自动装配将会装配 Bean 的所有属性。然而 , 若只希望装配个别属性时 , autowire 属性就不够灵活了。
  2. autowire 属性要么根据类型自动装配 , 要么根据名称自动装配 , 不能二者兼有。