【问题描述】当我们在使用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自己就知道注入哪种类型的对象。当当当当。。。。。Spring这么smart的开源框架,早就给大家想到了。。。。他就是autowire
Spring的bean有一个autowire的属性,它可以为以下的6个值。
一般,我们在使用的时候都会用byName,这种也就是说,当我们定义bean的时候,在给bean取名的时候,约定俗成的讲bean的id设置成首字母小写的类名。在我上面的例子里面即是testBean和testAction,这样当我们在testAction里面要自动注入TestBean的时候。就要在里面写一个Set方法,当然set方法的命名也是有规范的,那就是要set+类名,这里即是setTestBean。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>有的人可能还会嫌麻烦,因为这样,每一个bean都要加上这一句,很多余,哈哈哈哈,spring项目组也给大家想到了,那就是看如下: <?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>
Okay,问题完美解决。。。。。。。。。