Spring入门第六课
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入门第六课的更多相关文章
- Spring入门第五课
集合属性 在Spring中可以通过一组内置的xml标签(如:<list>,<set>,<map>)来配置集合属性. 配置java.util.List类型的属性,需要 ...
- Spring入门第四课
注入参数详解:null值和级联属性 可以使用专用的<null/>元素标签为Bean的字符串或其他对象类型的属性注入null值. 和Struts,Hiberante等框架一样,Spring支 ...
- Spring入门第三课
属性注入 属性注入就是通过setter方法注入Bean的属性值或依赖的对象. 属性植入使用<property>元素,使用name属性指定Bean的属性名称,value属性或者<val ...
- Spring入门第十三课
通过FactoryBean来配置Bean package logan.spring.study.factoryBean; public class Car { private String brand ...
- Spring入门第十一课
IOC容器中Bean的生命周期 Spring IOC容器可以管理Bean的生命周期,Spring允许在Bean生命周期的特定点执行定制的任务. Spring IOC容器对Bean的生命周期进行管理的过 ...
- Spring入门第十课
Spring表达式语言:SpEL Spring表达式语言(简称SpEL)是一个支持运行时查询和操作对象图的强大的表达式语言. 语法类似于EL:SpEL使用#{...}作为定界符,所有在大括号中的字符都 ...
- Spring入门第八课
看如下代码 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http:// ...
- Spring入门第七课
Bean之间的关系:继承和依赖. 继承Bean配置 Spring允许继承bean的配置,被继承的bean称为父bean,继承这个父bean的Bean称为子Bean. 子Bean从父Bean中继承配置, ...
- Spring入门第十七课
AOP编程 问题: 代码混乱: 越来越多的非业务需求(日志和验证等)加入后,原有的业务方法急剧膨胀,每个方法在处理核心逻辑的同事还必须兼顾其他多个关注点. 代码分散:以日志需求为例,只是为了满足这个单 ...
随机推荐
- linux学习-文件打包与压缩
- (转)Java字符串转日期或日期转字符串
文章中,用的API是SimpleDateFormat,它是属于java.text.SimpleDateFormat,所以请记得import进 来! 用法: SimpleDateFormat sdf = ...
- GeoServer基础教程(二):GeoServer的Web管理界面快速入门
转载:http://blog.163.com/daimiao_study/blog/static/248923117201542522742373/ GeoServer的控制和管理是基于网页形式,所有 ...
- L99
You're not obligated to win. You're obligated to keep trying.你不一定要获胜,但你必须不断尝试.He announced an expans ...
- 关于MFC的DLL调用方法问题
参考资料: 一.dll导出方式: MFC的DLL函数导出方法有两种:一种是通过模块定义文件DEF文件:另一种是在导出函数前加_declspec(dllexport). 1.def文件方法: 只需要在E ...
- 08 - Django应用第五步
1 自动测试 自动测试与测试的不同在于, 自动测试的测试工作是交给系统完成的 测试也有分类和级别, 有的用于一些细微的细节, 有的是针对整个软件整体 测试会保证一些看起来正常运行的功能在实际的多种情况 ...
- Cannot resolve class or package 'springframework' less... (Ctrl+F1) Inspection info:Spring XML mode
其实这个问题是由于MySQL 这个jar 包依赖类型默认是runtime ,也就是说只有运行时生效,所以虽然这里报错,但是不影响你代码运行. 解决方案: 将runtime 修改为Compile 即可 ...
- #include <deque>
deque \(deque\)头文件主要包括一个双端队列容器.是一个支持在两端插入两端删除的线性储存空间,与vector和queue相似.与\(vector\)比起来,\(deque\)可以在\(O( ...
- BZOJ2428:[HAOI2006]均分数据
我对模拟退火的理解:https://www.cnblogs.com/AKMer/p/9580982.html 题目传送门:https://www.lydsy.com/JudgeOnline/probl ...
- bzoj 1070 修车 —— 费用流
题目:https://www.lydsy.com/JudgeOnline/problem.php?id=1070 需要考虑前面修的车对后面等待的车造成的时间增加: 其实可以从每个人修车的顺序考虑,如果 ...