Spring学习笔记(七)模拟实际开发过程的调用过程XML版-Setter方式注入
模拟实际开发过程的调用过程XML版-Setter方式注入
源码获取github
1.项目结构
2.jar包跟上个一样
3.重写set方法
UserServiceImpl.java
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
beans.xml
<bean id="userDaoImpl" class="com.hs.dao.impl.UserDaoImpl"/>
<!--相当于userDao = new 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
private UserService userService;
public void setUserService(UserService userService) {
this.userService = userService;
}
beans.xml
<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.测试
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 {
@Test
public void test01() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
UserController controller = applicationContext.getBean("userController", UserController.class);
controller.add();
}
}
控制台输出:
UserController层—>ADD
UserService层的实现类—>ADD
UserDao层的实现类—>ADD