标题 基于XML 的bean 的自动装配举例
配置beans.xml
<!-- 基于xml 的bean的自动装配演示autowire="byType" 表示根据类型进行自动组装--> <!-- <bean id="orderAction" autowire="byType" class="com.spring.action.OrderAction" />--> <!-- 基于xml 的bean 的自动装配演示 1. autowire = "byName" 会自动去找id 为setXxxx 后面Xxxx 的bean 自动组装 ,如果找到就装配,如果找不到就报错, 比如这里的 2. <bean id="orderAction" autowire="byName" class="com.bean.OrderAction" /> 就会去找OrderAction 类中定义的setOrderService 的id 为orderService 的 OrderServicebean 组装,找到就组装,找不到就组装失败 --> <bean id="orderAction" autowire="byName" class="com.spring.action.OrderAction"/> <bean id="orderService" autowire="byName" class="com.spring.service.OrderService"/> <bean id="orderDao" class="com.spring.dao.OrderDao"/>
public class OrderDao { public void saveOrder() { System.out.println("保存..."); } }
import com.spring.dao.OrderDao; public class OrderService { private OrderDao orderDao; public OrderDao getOrderDao() { return orderDao; } public void setOrderDao(OrderDao orderDao) { this.orderDao = orderDao; } }
public class OrderAction { private OrderService orderService; public OrderService getOrderService() { return orderService; } public void setOrderService(OrderService orderService) { this.orderService = orderService; } }
测试
@Test public void setProByAutowire() { ApplicationContext ioc = new ClassPathXmlApplicationContext("beans.xml"); OrderAction orderAction = ioc.getBean("orderAction", OrderAction.class); orderAction.getOrderService().getOrderDao().saveOrder(); }