XML配置里的Bean自动装配

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

ByType(根据类型自动装配):若IOC容器中有多个与目标Bean类型一致的的Bean,在这种情况下,Spring将无法判定哪个Bean最适合该属性,所以不能执行自动装配。

byname(根据名称自动装配):必须将目标Bean的名称和属性名设置为完全相同。

Constructor(通过构造器自动转配):当Bean中存在多个构造器时,此种自动装配方式将会很复杂,不推荐使用。

下面看如何配置

package logan.spring.study.autowire;

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 logan.spring.study.autowire;

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 logan.spring.study.autowire;

public class Car {

    private String brand;
private String price;
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
@Override
public String toString() {
return "Car [brand=" + brand + ", price=" + price + "]";
} }
<?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="address" class="logan.spring.study.autowire.Address"
p:city="Beijing" p:street="HuiLongGuan"></bean> <bean id="car" class="logan.spring.study.autowire.Car"
p:brand="Audi" p:price="300000"></bean> <bean id="person" class="logan.spring.study.autowire.Person"
p:name="Tom" autowire="byName"></bean> </beans>
package logan.spring.study.autowire;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) {
// TODO Auto-generated method stub ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-autowire.xml");
Person person = (Person) ctx.getBean("person");
System.out.println(person); } }

下面是输出结果

五月 20, 2017 3:41:56 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@3eb07fd3: startup date [Sat May 20 15:41:56 CST 2017]; root of context hierarchy
五月 20, 2017 3:41:56 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [beans-autowire.xml]
Person [name=Tom, address=Address [city=Beijing, street=HuiLongGuan], car=Car [brand=Audi, price=300000]]

如果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: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="address2" class="logan.spring.study.autowire.Address"
p:city="Beijing" p:street="HuiLongGuan"></bean> <bean id="car" class="logan.spring.study.autowire.Car"
p:brand="Audi" p:price="300000"></bean> <bean id="person" class="logan.spring.study.autowire.Person"
p:name="Tom" autowire="byName"></bean> </beans>

输出结果为

五月 20, 2017 3:43:15 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@3eb07fd3: startup date [Sat May 20 15:43:15 CST 2017]; root of context hierarchy
五月 20, 2017 3:43:15 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [beans-autowire.xml]
Person [name=Tom, address=null, car=Car [brand=Audi, price=300000]]

可见这是根据名字来自动装配,如果地址address的id不是address就没有办法装配。

还可以根据类型来装配,如下:

<?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="address2" class="logan.spring.study.autowire.Address"
p:city="Beijing" p:street="HuiLongGuan"></bean> <bean id="car" class="logan.spring.study.autowire.Car"
p:brand="Audi" p:price="300000"></bean> <bean id="person" class="logan.spring.study.autowire.Person"
p:name="Tom" autowire="byType"></bean> </beans>

输出结果:

五月 20, 2017 3:47:08 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@3eb07fd3: startup date [Sat May 20 15:47:08 CST 2017]; root of context hierarchy
五月 20, 2017 3:47:08 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [beans-autowire.xml]
Person [name=Tom, address=Address [city=Beijing, street=HuiLongGuan], car=Car [brand=Audi, price=300000]]

但是根据类型装配有的时候会有问题,例如在xml里面配置两个相同类型的bean。

<?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="address2" class="logan.spring.study.autowire.Address"
p:city="Beijing" p:street="HuiLongGuan"></bean> <bean id="address3" class="logan.spring.study.autowire.Address"
p:city="Beijing" p:street="HuiLongGuan"></bean> <bean id="car" class="logan.spring.study.autowire.Car"
p:brand="Audi" p:price="300000"></bean> <bean id="person" class="logan.spring.study.autowire.Person"
p:name="Tom" autowire="byType"></bean> </beans>

报错如下:

五月 20, 2017 3:48:29 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@3eb07fd3: startup date [Sat May 20 15:48:29 CST 2017]; root of context hierarchy
五月 20, 2017 3:48:29 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [beans-autowire.xml]
五月 20, 2017 3:48:29 下午 org.springframework.context.support.ClassPathXmlApplicationContext refresh
警告: 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-autowire.xml]: Unsatisfied dependency expressed through bean property 'address'; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'logan.spring.study.autowire.Address' available: expected single matching bean but found 2: address2,address3
Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'person' defined in class path resource [beans-autowire.xml]: Unsatisfied dependency expressed through bean property 'address'; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'logan.spring.study.autowire.Address' available: expected single matching bean but found 2: address2,address3
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 logan.spring.study.autowire.Main.main(Main.java:11)
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'logan.spring.study.autowire.Address' available: expected single matching bean but found 2: address2,address3
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自动装配的缺点:

在Bean配置文件里配置autowire属性进行自动装配将会装配Bean的所有属性,然而,若只希望装配个别属性时,autowire就不够灵活了。

autowire属性要么根据类型自动装配,要么根据名称自动装配。不能两者兼而有之。

一般情况下,在实际的项目中很少使用自动装配,因为和自动装配功能所带来的好处比起来,明确清晰的配置文档更有说服力一些。

Spring入门第六课的更多相关文章

  1. Spring入门第五课

    集合属性 在Spring中可以通过一组内置的xml标签(如:<list>,<set>,<map>)来配置集合属性. 配置java.util.List类型的属性,需要 ...

  2. Spring入门第四课

    注入参数详解:null值和级联属性 可以使用专用的<null/>元素标签为Bean的字符串或其他对象类型的属性注入null值. 和Struts,Hiberante等框架一样,Spring支 ...

  3. Spring入门第三课

    属性注入 属性注入就是通过setter方法注入Bean的属性值或依赖的对象. 属性植入使用<property>元素,使用name属性指定Bean的属性名称,value属性或者<val ...

  4. Spring入门第十三课

    通过FactoryBean来配置Bean package logan.spring.study.factoryBean; public class Car { private String brand ...

  5. Spring入门第十一课

    IOC容器中Bean的生命周期 Spring IOC容器可以管理Bean的生命周期,Spring允许在Bean生命周期的特定点执行定制的任务. Spring IOC容器对Bean的生命周期进行管理的过 ...

  6. Spring入门第十课

    Spring表达式语言:SpEL Spring表达式语言(简称SpEL)是一个支持运行时查询和操作对象图的强大的表达式语言. 语法类似于EL:SpEL使用#{...}作为定界符,所有在大括号中的字符都 ...

  7. Spring入门第八课

    看如下代码 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http:// ...

  8. Spring入门第七课

    Bean之间的关系:继承和依赖. 继承Bean配置 Spring允许继承bean的配置,被继承的bean称为父bean,继承这个父bean的Bean称为子Bean. 子Bean从父Bean中继承配置, ...

  9. Spring入门第十七课

    AOP编程 问题: 代码混乱: 越来越多的非业务需求(日志和验证等)加入后,原有的业务方法急剧膨胀,每个方法在处理核心逻辑的同事还必须兼顾其他多个关注点. 代码分散:以日志需求为例,只是为了满足这个单 ...

随机推荐

  1. hd acm1061

    Problem Description Given a positive integer N, you should output the most right digit of N^N.   Inp ...

  2. ThinkPHP的Auth类认证

    Auth 类已经在ThinkPHP代码仓库中存在很久了,但是因为一直没有出过它的教程, 很少人知道它, 它其实比RBAC更方便 .  RBAC是按节点进行认证的,如果要控制比节点更细的权限就有点困难了 ...

  3. 《机器学习实战》学习笔记第十四章 —— 利用SVD简化数据

    相关博客: 吴恩达机器学习笔记(八) —— 降维与主成分分析法(PCA) <机器学习实战>学习笔记第十三章 —— 利用PCA来简化数据 奇异值分解(SVD)原理与在降维中的应用 机器学习( ...

  4. 在我的电脑右键 Manage 拒绝访问的解决方法

    为什么我的电脑右键里的“管理”会变成“manage”啦.原来是中文的,点了之后出来一个对话框,标题是“桌面”说是“拒绝访问” 是系统环境变量里少了 windir=C:\WINDOWS 方法是:打开系统 ...

  5. docker仓库及数据卷

    docker help rmi, 删除本地镜像 docker run -it --name=centos centos:latest /bin/sh  --name的选项可以方便我们以后引用此imag ...

  6. matlab函数之imresize()

    B = imresize(A,scale) B = imresize(A,scale) 返回图像 B,它是将 A 的长宽大小缩放 scale 倍之后的图像.输入图像 A 可以是灰度.RGB 或二值图像 ...

  7. java 中的拦截器和过滤器

    区别: 1.拦截器是基于java的反射机制的,而过滤器是基于函数回调 2.过滤器依赖与servlet容器,而拦截器不依赖与servlet容器 3.拦截器只能对action请求起作用,而过滤器则可以对几 ...

  8. 如何在node.js中使用neo4j

    本章中你将会学到如何在node.js中使用neo4j图形数据库. 当你想存储或者查询和数据紧密关联的数据的时候,图形数据库很有用. neo4j是一个可有效存储,处理和查询你数据模型中紧密相连的元素的数 ...

  9. Ubuntu 下安装mysql

    本文引用自 https://www.cnblogs.com/jpfss/p/7944622.html 此篇为http://www.cnblogs.com/EasonJim/p/7139275.html ...

  10. 【leetcode刷题笔记】Recover Binary Search Tree

    Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing ...