模拟实际开发过程的调用过程XML版-Setter方式注入
源码获取github
[TOC]
1.项目结构
2.jar包跟上个一样
3.重写set方法
UserServiceImpl.java
1 2 3 4 5
|
private UserDao userDao;
public void (UserDao userDao) { this.userDao = userDao; }
|
beans.xml
1 2 3 4 5 6 7
|
<bean id="userDaoImpl" class="com.hs.dao.impl.UserDaoImpl"/>
<bean id="userServiceImpl" class="com.hs.service.impl.UserServiceImpl"> <property name="userDao"> <ref bean="userDaoImpl"/> </property> </bean>
|
在set方法里代替完成了,private UserDao userDao = new userDaoImpl();
UserController.java
1 2 3 4 5
|
private UserService userService;
public void setUserService(UserService userService) { this.userService = userService; }
|
beans.xml
1 2 3 4 5 6 7 8 9 10大专栏 Spring学习笔记(七)模拟实际开发过程的调用过程XML版-Setter方式注入/span> 11
|
<bean id="userServiceImpl" class="com.hs.service.impl.UserServiceImpl"> <property name="userDao"> <ref bean="userDaoImpl"/> </property> </bean> <!--先UserController = new UserController() 再userService = new userServiceImpl(); --> <bean id="userController" class="com.hs.web.UserController" p:userService-ref="userServiceImpl"> <!--<property name="userService" ref="userServiceImpl"/>--> </bean>
|
在set方法里代替完成了private UserService userService = new userServiceImpl();
4.测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
package com.hs.test;
import com.hs.web.UserController; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MethodTest {
public void test01() { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml"); UserController controller = applicationContext.getBean("userController", UserController.class); controller.add(); } }
|
控制台输出:
UserController层—>ADD
UserService层的实现类—>ADD
UserDao层的实现类—>ADD