问题描述
如果一个bean里有很多属性,每个属性都要手动加property节点显式注入属性值,就很麻烦。
解决方案
让IOC容器自动为bean指定引用
方法一:在XML配置文件里实现autowire(不会用的多,容易出错)
autowire默认值为no。
1.byName:根据属性名自动装配。此选项将检查容器并根据名字查找与属性完全一致的bean,并将其与属性自动装配。例如,在bean定义中将autowire设置为byName,而该bean包含master属性(同时提供setMaster(..)方法),Spring就会查找名为master的bean定义,并用它来装配给master属性。
<bean id="userDao1" class="com.dao.impl.UserDaoImpl" scope="prototype">
<property name="daoId" value="1"></property>
</bean>
<bean id="userDao2" class="com.dao.impl.UserDaoImpl" scope="prototype">
<property name="daoId" value="2"></property>
</bean>
<bean id="userService" class="com.service.UserService" autowire="byName">
test类,IOC容器根据方法名getUserDao1,自动转为属性名userDao1,去XML里查找对应bean的id。
ApplicationContext factory = new ClassPathXmlApplicationContext("beans.xml");
UserService service = (UserService) factory.getBean("userService");
System.out.println(service.getUserDao1().toString());
2.byType:如果容器中存在一个与指定属性类型相同的bean,那么将与该属性自动装配。如果存在多个该类型的bean,那么将会抛出异常,并指出不能使用byType方式进行自动装配。若没有找到相匹配的bean,则什么事都不发生,属性也不会被设置。如果你不希望这样,那么可以通过设置dependency-check=”objects”让Spring抛出异常。
constructor与autodetect省略。
只要将对应的UserDaoImpl删去一个就可以。
<bean id="userDao1" class="com.dao.impl.UserDaoImpl" scope="prototype">
<property name="daoId" value="1"></property>
</bean>
<bean id="userService" class="com.service.UserService" autowire="byName">
如果所有的bean都用同一种autowire,则可以使用beans的属性:default-autowire。
<?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-2.5.xsd"
default-autowire="byName">