共有三种注入类型 一种是set注入 一种是构造注入 一种是接口注入 最常用的还是set 现在看一下construct
构造注入
在userservice中加入
package com.bjsxt.service; import com.bjsxt.dao.UserDAO; import com.bjsxt.model.User; public class UserService { private UserDAO userDAO; public void add(User user) { userDAO.save(user); } public UserDAO getUserDAO() { return userDAO; } public void setUserDAO(UserDAO userDAO) { this.userDAO = userDAO; } public UserService(UserDAO userDAO) { super(); this.userDAO = userDAO; } }
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-2.5.xsd"> <bean id="u" class="com.bjsxt.dao.impl.UserDAOImpl"> </bean> <bean id="userService" class="com.bjsxt.service.UserService"> <!-- <property name="userDAO" ref="u" /> --> <constructor-arg> <ref bean="u"/> </constructor-arg> </bean> </beans>
测试代码
@Test public void testAdd() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); UserService service = (UserService)ctx.getBean("userService"); User u = new User(); u.setUsername("zhangsan"); u.setPassword("zhangsan"); service.add(u); }
这样也是可以成功注入impl的