【问题描述】当我们在使用Spring的IOC功能的时候,Spring提供了集中注入方式:属性注入,构造函数注入和工厂方法注入,我们更多的时候是使用的属性注入,即set方法注入。使用set方法注入要求我们在写bean的配置文件的时候,需要我们手动设置properties。诸如:
- <?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-3.0.xsd">
- <bean id="testBean" class="com.jack.TestBean" scope="prototype"/>
- <bean id="testAction" class="com.jack.TestAction" scope="prototype">
- <property name="testBean" ref="testBean"/>
- </bean>
- </beans>
- 这样使用Spring起来相当麻烦。
【问题分析以及解决办法】我们在想,会不会有那种自动注入的方法呢?就是不用我们在Spring配置文件里面写入
- <property name="testBean" ref="testBean"/>
当当当当。。。。。Spring这么smart的开源框架,早就给大家想到了。。。。他就是autowire
Spring的bean有一个autowire的属性,它可以为以下的6个值。
- 1、 No:即不启用自动装配。Autowire默认的值。
- 2、 byName:通过属性的名字的方式查找JavaBean依赖的对象并为其注入。比如说类Computer有个属性printer,指定其autowire属性为byName后,Spring IoC容器会在配置文件中查找id/name属性为printer的bean,然后使用Seter方法为其注入。
- 3、 byType:通过属性的类型查找JavaBean依赖的对象并为其注入。比如类Computer有个属性printer,类型为Printer,那么,指定其autowire属性为byType后,Spring IoC容器会查找Class属性为Printer的bean,使用Seter方法为其注入。
- 4、 constructor:通byType一样,也是通过类型查找依赖对象。与byType的区别在于它不是使用Seter方法注入,而是使用构造子注入。
- 5、 autodetect:在byType和constructor之间自动的选择注入方式。
- 6、 default:由上级标签<beans>的default-autowire属性确定
-
- package com.jack;
- /**
- * @author Jack Zhang
- * @version vb1.0
- * @Email virgoboy2004@163.com
- * @Date 2012-5-1
- */
- public class TestAction
- {
- private TestBean testBean;
- public void setTestBean(TestBean testBean)
- {
- this.testBean = testBean;
- }
- public String execute()
- {
- testBean.getCode();
- return "json";
- }
- }
-
- <?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-3.0.xsd">
- <bean id="testBean" class="com.jack.TestBean" scope="prototype"/>
- <bean id="testAction" class="com.jack.TestAction" scope="prototype"autowire="byName"/>
- </beans>
- <?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"
- default-autowire="byName"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
- <bean id="testBean" class="com.jack.TestBean" scope="prototype"/>
- <bean id="testAction" class="com.jack.TestAction" scope="prototype"/>
- </beans>
很好的文章,最起码我读懂了,给大家分享。ps:http://blog.youkuaiyun.com/virgoboy2004/article/details/7525795