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编程 问题: 代码混乱: 越来越多的非业务需求(日志和验证等)加入后,原有的业务方法急剧膨胀,每个方法在处理核心逻辑的同事还必须兼顾其他多个关注点. 代码分散:以日志需求为例,只是为了满足这个单 ...
随机推荐
- ansible普通用户su切换问题
在现网应用中,安全加固后的主机是不允许直接以root用户登陆的,而很多命令又需要root用户来执行,在不改造现网的情况下.希望通过一个普通用户先登陆,再su切到root执行.而且每台主机的普通用户和r ...
- wget 监控web服务器
wget --timeout=$timeout --tries=$times $url -q &>/dev/null --timeout=number 设定超时时间 --tries=nu ...
- 初步了解Spark生态系统及Spark Streaming
一. 场景 ◆ Spark[4]: Scope: a MapReduce-like cluster computing framework designed for low-laten ...
- Hadoop-HA配置详细步骤
1. HA服务器配置 对hdfs做高可用 1.1服务器详情 服务器:centos7 Hadoop:2.6.5 Jdk:1.8 共四台服务器 192.168.1.111 node1 192.168.1. ...
- 亚马逊EC2服务器登录方法
1.根据官网提供的方法登录连接到EC2服务器(官网推荐windows用户使用PUTTY连接) 2. 创建root的密码,输入如下命令: sudo passwd root 3.然后会提示你输入new p ...
- ruanjiangongcheng1
软体工程的方法有很多方面的意义.包括专案管理,分析,设计,程序的编写,测试和质量控制. 软体设计方法可以区别为重量级的方法和轻量级的方法.重量级的方法中产生大量的正式文档. 著名的重量级开发方法包括I ...
- 未测试 Delphi读写UTF-8、Unicode格式文本文件
// UTF-8文件写入函数 procedure SaveUTFFile(const FileName: string; S: string; WriteHeader: Boolean = True) ...
- JS获取ListBox所有项
JS代码: var listbox = document.getElementById("<%=lbCustom.ClientID %>"); var values = ...
- getline()函数详解 (2013-03-26 17:19:58)
学习C++的同学可能都会遇到一个getline()函数,譬如在C++premer中,标准string类型第二小节就是“用getline读取整行文本”.书上给的程序如下: int main() { ...
- java是用utf-16be编码方式编的。中文和英文都是两个字节