根据名称自动装配:autowire="byName"
-自动去IOC容器中找与属性名同名的引用的对象,并自动注入
package loaderman.d_auto; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class App { // 创建容器对象 private ApplicationContext ac = new ClassPathXmlApplicationContext("loaderman/d_auto/bean.xml"); @Test public void testExecuteAction() { // 从容器中获取Action UserAction userAction = (UserAction) ac.getBean("userAction"); userAction.execute(); } }
package loaderman.d_auto; public class UserAction { // Service: springIOC容器注入 private UserService userService; public void setUserService(UserService userService) { this.userService = userService; } public String execute() { userService.save(); return null; } }
package loaderman.d_auto; public class UserDao { public void save() { System.out.println("DB:保存用户"); } }
package loaderman.d_auto; public class UserService { private UserDao userDao; // = new UserDao(); // IOC:对象的创建交给spring的外部容器完成 public void setUserDao(UserDao userDao) { this.userDao = userDao; } public void save() { userDao.save(); } }
<?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" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd" default-autowire="byType"> <!-- ###############自动装配############### --> <bean id="userDao" class="loaderman.d_auto.UserDao"></bean> <bean id="userService" class="loaderman.d_auto.UserService"></bean> <!-- 如果根据类型自动装配: 必须确保IOC容器中只有一个该类型的对象 --> <bean id="userAction" class="loaderman.d_auto.UserAction"></bean> <!-- 报错: 因为上面已经有一个该类型的对象,且使用了根据类型自动装配 <bean id="userService_test" class="loaderman.d_auto.UserService" autowire="byType"></bean> --> </beans>
总结:
Spring提供的自动装配主要是为了简化配置; 但是不利于后期的维护。
(一般不推荐使用)