与设值注入相似 ,只需改动一下两个文件
1.UserServiceImpl中代码添加构造方法:
public class UserServiceImpl implements UserService { private UserDao userDao; //构造器注入 public UserServiceImpl(UserDao userDao){ this.userDao=userDao; } // //设值注入 // public void setUserDao(UserDao userDao) { // this.userDao = userDao; // } @Override public void save(String arg) { System.out.println("userServiceImpl接受参数:"+arg); arg=arg+":"+this.hashCode(); userDao.save(arg); } }View Code
2.修改Bean.xml 改为构造注入
<?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-3.0.xsd"> <!-- <bean id="userService" class="test.UserServiceImpl">--> <!-- <property name="userDao" ref="userDao"/>--> <!-- </bean>--> <bean id="userDao" class="test.UserDaoImpl"></bean> <bean id="userService" class="test.UserServiceImpl"> <constructor-arg name="userDao" ref="userDao"/> </bean> </beans>View Code
3.其他代码不动,TestMain运行结果: