Spring学习札记 使用XML配置实现Bean的auto-wiring (自动绑定)
Spring在配置过程中可以实现Bean的引用类型属性与其他已定义好的Bean的自动关联,除了可以减少手工输入外,还可以实现应用的动态构建。不过大多数时候需要整个应用遵循特定的开发规则与命名规则,否则很容易造成程序难于理解与混乱。很多人更愿意多做点工作也不愿意造成代码调试的困难。如果要实现自动关联,很简单,XML配置方式只需要在Bean标签中加入autowire属性即可。而且这种关联不仅仅限制与Bean的属性,对于Bean的构造方法的参数也可以实现自动关联。
以下是用来示例的两个类,MessageLooper中有一个Message类型的引用属性。
XML配置autowire属性有5个模式可以选择:
1.no 即不进行自动关联
2.byName通过具有与property(属性)名相等id或name值的Bean进行关联。如果没有发现可以关联的Bean,则使property值留空(null)。
3.byType通过具有与property(属性)相同类型的Bean进行关联。如果没有发现可以关联的Bean,则使property属性值留空(null),如果发现多个匹配的Bean则会抛出 org.springframework.beans.factory.UnsatisfiedDependencyException异常。
4.constructor通过byType模式对构造方法中的参数进行关联。如果有多个构造函数,则匹配参数个数最多的构造函数。
5.autodetect优先使用constructor模式进行关联,没有可以关联的构造方法则是用byType模式进行关联。 在spring3中已经放弃使用autodetect模式。
要实现MessageLooper中对Message类型属性的自动关联,请看以下XML中messageLooper的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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <!-- <bean id="messageLooper" class="autowiring.MessageLooper" autowire="byType" > <property name="message" ref="message" /> //此处为使用手动关联的代码 </bean> --> <bean id="messageLooper" class="autowiring.MessageLooper" autowire="byName" /> <bean id="message" class="autowiring.Message" > <property name="messageContent" value="How are you?" /> </bean> </beans>
对于byType模式与constructor模式如果有多个可以匹配的Bean存在,又想使自动匹配成功,可以在符合匹配条件但又不想被匹配的Bean中加入 autowire-candidate="false",如下:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="messageLooper" class="autowiring.MessageLooper" autowire="byType" /> <bean id="message" class="autowiring.Message" > <property name="messageContent" value="How are you?" /> </bean> <bean id="message2" class="autowiring.Message" autowire-candidate="false" > <property name="messageContent" value="How are you ???" /> </bean> </beans>
这样message2就不会参与匹配,这样也不会因为有多个符合匹配的Bean而抛出异常。