Spring Autowire
2017-01-18 14:43
609 查看
Autowire:自动装配
autowire的实现方式有2种,但是其最终是通过autoWire来修饰bean,并让bean在上下文中具有自动装配的能力.
实现autowire的方法有2种:
第一种在配置直接配置beanxml文件,如:<beanid="customer"class="com.ric.demo.Customer"autowire="constructor"></bean>
autowire的实现方式有2种,但是其最终是通过autoWire来修饰bean,并让bean在上下文中具有自动装配的能力.
实现autowire的方法有2种:
第一种在配置直接配置beanxml文件,如:<beanid="customer"class="com.ric.demo.Customer"autowire="constructor"></bean>
<beanid="person"class="com.ric.demo.Person"> <propertyname="name"value="john"/> <propertyname="age"value="20"/> <propertyname="gender"value="1"/> </bean> 这种方式可以让bean在上下文中通过autowire的值判断自动装配规则,byName是通过名字匹配,byType是通过类型匹配(这时候上下文中只能有一种这种类型的bean否则会报错),default(不会装配),contructor(根据构造器来装配,这时候会把上下文中同名的bean当作参数传入构造器中来装配) 第二种:通过@Autowired注解来实现,这种实现方式需要在自动装配的地方加上@Autowired来修饰,然后具体spring如何扫描呢: 1、通过org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor来实现,在定义beans的上下文中加上 <beanclass="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor">来处理 2、把xml中这个bean对应的xml配置给注释掉,并在beans中加上自动扫描的包,然后在要装配的bean的class前加上@Component,对应的属性上加上@Autowired就可以了。 两种方式都是通过将bean置于上下文中,这样context可以通过扫描或者配置来给对应的bean自动装配,关键是要让你要暴露的bean置于上下文当中 这种通过@Autowired注解(包括以上1,2)来自动装配时@Autowired可以这样@Autowired(required=false)来修饰你的自动装配是不是必要的,如果为false时那么当被装配的属性为空不会出现异常报错。这时还有另外一个注解配合使用能够实现第一种方法中的byName的方式。eg. @Autowired(required=false)//装配不上时不会出现异常 @Qualifier("PersonBean1")//匹配上下文与Qualifier中参数相同名的bean
相关文章推荐
- 关于Spring,default-autowire-candidates属性的作用验证
- spring03autowire属性
- struts.objectFactory和struts.objectFactory.spring.autoWire
- SpringXML方式配置bean的自动装配autowire
- Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: privat
- 如何使用spring的autowire为servlet注入bean
- spring 自动装配 default-autowire="byName/byType"
- 简单明了介绍Spring手工注入@autowire用法 及 beans.xml配置区别
- Spring学习记录(三)---bean自动装配autowire
- Spring如何实现自动依赖注入-------autowire
- Spring Autowire自动装配
- Spring 几种 autowire的区别
- Spring autowire 自动装配简介
- Spring 自动依赖注入优化(autowire-candidate)
- 11级_Java_曹建波 05.06 Spring的autowire自动装配bean的四种方式
- Java Spring Tutorial -- autowire byName, byType, constructor
- spring中@Resource和@Autowire的区别
- Spring——@Autowire冲突问题
- Spring Autowire自动装配
- spring与springboot中,如何在static方法里用@Autowire或者@Resource注入的属性