`
kuaile863
  • 浏览: 114484 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Spring自动装配(autowire)麻烦吗?(一)

阅读更多

Spring自动装配(autowire)麻烦吗?

简单介绍一下Spring autowire(自动装配)那首先问问你,你觉得springautowire(自动装配)好吗?

如果使用它可能会降低可读性和可维护性,但是spring中类与类之间的依赖都用<ref>标签来连接,这样太费事了。那你如何选择呢?

 

下面介绍Spring为我们提供了autowire(自动装配)的属性。

 

  spring配置文件中autowire属性值如下:

1no解析

不使用自动装配,是autowire默认的值。必须通过ref元素指定依赖,这是默认设置。

案例:

//spring中 app.xml的设置
<!-- 定义一个empServiceImpl的javabean实例 -->
	<bean id="empServiceImpl" class="com.csdn.service.EmpServiceImpl">
	<property name="name">
	<value>Nan</value></property>
	</bean>
<!-- 定义一个hourEmpServiceImpl的javabean实例,实现empServiceImpl的业务层  -->
<bean id="hourEmpServiceImpl" class="com.csdn.service.HourEmpServiceImpl" autowire="no"  >
<!—autowire的定义为no代表实现其它类时需要用ref -->
	<property name="empServiceImpl" ref="empServiceImpl"></property>
	</bean>
//empServiceImpl的代码
package com.csdn.service;
public class EmpServiceImpl {
/**定义一个变量实例*/
private String name;
/**通过set方法进行赋值*/
	public void setName(String name) {
	this.name = name;
	}
}
// hourEmpServiceImpl的代码
package com.csdn.service;
public class HourEmpServiceImpl {
/**定义一个EmpServiceImpl的操作对象*/
	private EmpServiceImpl empServiceImpl;
/**生成相应的set方法  通过set方法注入的*/
	public void setEmpServiceImpl(EmpServiceImpl empServiceImpl) {
		this.empServiceImpl = empServiceImpl;
	}
}
//junit测试类代码
 @Test
public void test(){
ApplicationContext ac = new ClassPathXmlApplicationContext("app.xml");
HourEmpServiceImpl  hsi=(HourEmpServiceImpl) ac.getBean("hourEmpServiceImpl"); 
}

 

2byName解析

通过属性名的方式查找spring容器,检测javabean的名字与属性完全一致的bean,并将其与属性自动装配。

案例:

 

//spring中 app.xml的设置
<!-- 定义一个empServiceImpl的javabean实例 -->
	<bean id="empServiceImpl" class="com.csdn.service.EmpServiceImpl">
	<property name="name">
	<value>Nan</value></property>
	</bean>
<!-- 定义一个hourEmpServiceImpl的javabean实例,实现empServiceImpl的业务层  -->
<bean id="hourEmpServiceImpl" class="com.csdn.service.HourEmpServiceImpl" autowire="byName"  >
<!—autowire的定义为byName代表实现其它类,自动检测javabean的名字与属性完全一样的注意:如果实现的javabean没有在Spring的xml中实例,那么也不会报错只是为空值-->
</bean>
//empServiceImpl的代码
package com.csdn.service;
public class EmpServiceImpl {
/**定义一个变量实例*/
private String name;
/**通过set方法进行赋值*/
	public void setName(String name) {
	this.name = name;
	}
}
// hourEmpServiceImpl的代码
package com.csdn.service;
public class HourEmpServiceImpl {
/**定义一个EmpServiceImpl的操作对象*/
	private EmpServiceImpl empServiceImpl;
/**生成相应的set方法  通过set方法注入的*/
	public void setEmpServiceImpl(EmpServiceImpl empServiceImpl) {
		this.empServiceImpl = empServiceImpl;
	}
}
//junit测试类代码
 @Test
public void test(){
ApplicationContext ac = new ClassPathXmlApplicationContext("app.xml");
HourEmpServiceImpl  hsi=(HourEmpServiceImpl) ac.getBean("hourEmpServiceImpl"); 
}


 

3byType的解析

如果容器中存在一个与指定属性类型相同的bean,如果没有找到相符的bean,该属性就没有被装配上。如果存在多个该类型的bean,那么将会抛出异常,并指出不能使用byType方式进行自动装配。

案例:

//spring中 app.xml的设置
<!-- 定义一个empServiceImpl的javabean实例 -->
	<bean id="empServiceImpl" class="com.csdn.service.EmpServiceImpl">
	<property name="name">
	<value>Nan</value></property>
	</bean>
<!-- 定义一个HourAddressServiceImpl的javabean实例实现了EmpServiceImpl的javabean那么会出现bug:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'hourEmpServiceImpl' defined in class path resource [app.xml]: Unsatisfied dependency expressed through bean property 'empServiceImpl': : No unique bean of type [com.csdn.service.EmpServiceImpl] is defined: expected single matching bean but found 2: [empServiceImpl, com.csdn.service.HourAddressServiceImpl#0]; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.csdn.service.EmpServiceImpl] is defined: expected single matching bean but found 2: [empServiceImpl, com.csdn.service.HourAddressServiceImpl#0]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireByType(AbstractAutowireCapableBeanFactory.java:1091)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:982)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:472)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
	at java.security.AccessController.doPrivileged(Native Method)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
	at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:429)
	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:728)
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:380)
	at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
	at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
	at com.csdn.junit.EmpTest.test(EmpTest.java:13)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
	at java.lang.reflect.Method.invoke(Method.java:597)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
	at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
	at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:73)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:46)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:180)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:41)
	at org.junit.runners.ParentRunner$1.evaluate(ParentRunner.java:173)
	at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
	at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:220)
	at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:46)
	at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.csdn.service.EmpServiceImpl] is defined: expected single matching bean but found 2: [empServiceImpl, com.csdn.service.HourAddressServiceImpl#0]
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:621)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireByType(AbstractAutowireCapableBeanFactory.java:1076)
	... 40 more

	<bean class="com.csdn.service.HourAddressServiceImpl"></bean>
-->
<!-- 定义一个hourEmpServiceImpl的javabean实例,实现empServiceImpl的业务层  -->
<bean id="hourEmpServiceImpl" class="com.csdn.service.HourEmpServiceImpl" autowire="byType"  >
<!—autowire的定义为byType -->
</bean>
//empServiceImpl的代码
package com.csdn.service;
public class EmpServiceImpl {
/**定义一个变量实例*/
private String name;
/**通过set方法进行赋值*/
	public void setName(String name) {
	this.name = name;
	}
}
// hourEmpServiceImpl的代码
package com.csdn.service;
public class HourEmpServiceImpl {
/**定义一个EmpServiceImpl的操作对象*/
	private EmpServiceImpl empServiceImpl;
/**生成相应的set方法  通过set方法注入的*/
	public void setEmpServiceImpl(EmpServiceImpl empServiceImpl) {
		this.empServiceImpl = empServiceImpl;
	}
}
// HourAddressServiceImpl的代码
package com.csdn.service;
//这里只是继承了EmpServiceImpl的实例javabean
public class HourAddressServiceImpl extends EmpServiceImpl {
}
//junit测试类代码
 @Test
public void test(){
ApplicationContext ac = new ClassPathXmlApplicationContext("app.xml");
HourEmpServiceImpl  hsi=(HourEmpServiceImpl) ac.getBean("hourEmpServiceImpl"); 
}
注意:父类与子类匹配的方式是:子类自动装载成父类的对象。
	  接口与实现类:实现类的对象可以自动装载到接口的对象。否则会出现空指针异常。

 

1
7
分享到:
评论

相关推荐

    Spring自动装配的方式

    Spring自动装配的方式和举例、以及@Qualifier、@Autowire、@Resource的使用。

    springboot-autowire:学习springboot自动装配原理

    #学习springboot自动装配 ##一,手动装配 ### 1,模式注解装配 @Component注解,或者@Component注解的扩展,@ Controller,@ Service,存储库,@ Configruation等, ### 2. @ Configuration启动容器+ @ Bean注册...

    spring2.5学习PPT 传智博客

    08_编码剖析Spring装配基本属性的原理 09_Spring如何装配各种集合类型的属性 10_使用构造器装配属性 11_用@Resource注解完成属性装配 12_编码剖析@Resource注解的实现原理 13.@Autowire注解与自动装配 14.让...

    Jimmy-Ma#SpringDemo#004.自动装配(XML)1

    使用autowire属性指定自动装配的方式byName根据bean的名字和当前bean的setter风格属性名进行自动装配若有匹配,则自动转配若无匹配,则不装配

    Spring的学习笔记

    八、 自动装配autowire 13 (一) byName 13 (二) byType 14 (三) 注意 14 九、 生命周期 15 (一) lazy-init/default-lazy-init 15 (二) init-method destroy-method 不要和prototype一起用(了解) 15 第六课:...

    spring2.5 学习笔记

    八、 自动装配autowire 13 (一) byName 13 (二) byType 14 (三) 注意 14 九、 生命周期 15 (一) lazy-init/default-lazy-init 15 (二) init-method destroy-method 不要和prototype一起用(了解) 15 第六课:...

    Spring-Reference_zh_CN(Spring中文参考手册)

    3.3.6. 自动装配(autowire)协作者 3.3.6.1. 设置Bean使自动装配失效 3.3.7. 依赖检查 3.3.8. 方法注入 3.3.8.1. Lookup方法注入 3.3.8.2. 自定义方法的替代方案 3.4. bean的作用域 3.4.1. Singleton作用域 3.4.2. ...

    Spring 2.0 开发参考手册

    3.3.6. 自动装配(autowire)协作者 3.3.7. 依赖检查 3.3.8. 方法注入 3.4. bean的作用域 3.4.1. Singleton作用域 3.4.2. Prototype作用域 3.4.3. 其他作用域 3.4.4. 自定义作用域 3.5. 定制bean特性 3.5.1...

    Spring中文帮助文档

    3.3.5. 自动装配(autowire)协作者 3.3.6. 依赖检查 3.3.7. 方法注入 3.4. Bean的作用域 3.4.1. Singleton作用域 3.4.2. Prototype作用域 3.4.3. Singleton beans和prototype-bean的依赖 3.4.4. 其他作用域 ...

    Spring API

    3.3.5. 自动装配(autowire)协作者 3.3.6. 依赖检查 3.3.7. 方法注入 3.4. Bean的作用域 3.4.1. Singleton作用域 3.4.2. Prototype作用域 3.4.3. Singleton beans和prototype-bean的依赖 3.4.4. 其他作用域 ...

    spring chm文档

    3.3.6. 自动装配(autowire)协作者 3.3.7. 依赖检查 3.3.8. 方法注入 3.4. bean的作用域 3.4.1. Singleton作用域 3.4.2. Prototype作用域 3.4.3. 其他作用域 3.4.4. 自定义作用域 3.5. 定制bean特性 3.5.1...

    xmljava系统源码-SpringInAction4:《SpringInAction4th》学习笔记

    可以在一个应用上下文中定义多个配置文件,每个配置文件设置自己的默认自动装配策略(default-autowire) 如果使用constructor自动装配策略,就不能混合使用constructor-arg 注解方式可以实现更细粒度的自动装配,...

    spring学习过程

    spring基础,主要讲解了 spring的autowire:自动装配 collections:属性配置的细节 properties:外部属性文件的使用 relati:bean之间的关系 scope:bean的作用域 spel:spel的使用

    尚学堂spring课程培训代码

    讲述的内容:aop, autowire(自动装配),动态代理、静态代理、注解、hibernate集成、struts集成等,欢迎关注我的其他资源!

    mockitobeans

    概述Mockitobeans是一个 ,通过使用Spring自己的@Autowire语法,您可以无缝地对所有bean进行自动装配。历史mockitobeans时,我一直在寻找一种方式来开始使用嘲笑说已经自动装配依赖其中有额外的自动装配Autowired的...

    Struts2属性文件详解

    指定Spring框架的自动装配模式, 该属性的默认值是name, 即默认根据Bean的name属性自动装配. struts.objectFactory.spring.useClassCache 该属性指定整合Spring框架时,是否缓存Bean实例,该属性只允许使用true和false...

Global site tag (gtag.js) - Google Analytics