package cn.edu.hpu.service; import cn.edu.hpu.dao.UserDao; import cn.edu.hpu.dao.Impl.UserDaoImpl; import cn.edu.hpu.model.User; public class UserService { private UserDao userDao; public UserDao getUserDao() { return userDao; } public void setUserDao(UserDao userDao) { this.userDao = userDao; } public void add(User u){ this.userDao.save(u); } }
<?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="cn.edu.hpu.dao.Impl.UserDaoImpl"> </bean> <bean id="userService" class="cn.edu.hpu.service.UserService"> <property name="userDao" ref="u" /> </bean> </beans>
@Test public void testAdd() throws Exception{ BeanFactory ctx=new ClassPathXmlApplicationContext("beans.xml"); UserService userService=(UserService)ctx.getBean("userService"); User u=new User(); u.setUsername("u1"); u.setPassword("p1"); userService.add(u); }测试成功!
例子:
UserService.java:
package cn.edu.hpu.service; import cn.edu.hpu.dao.UserDao; import cn.edu.hpu.dao.Impl.UserDaoImpl; import cn.edu.hpu.model.User; public class UserService { private UserDao userDao; public UserService(){ } public UserService(UserDao userDao){ super(); this.userDao=userDao; } }
<?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="cn.edu.hpu.dao.Impl.UserDaoImpl"> </bean> <bean id="userService" class="cn.edu.hpu.service.UserService"> <constructor-arg> <ref bean="u"/> </constructor-arg> </bean> </beans>
@Test public void testAdd() throws Exception{ BeanFactory ctx=new ClassPathXmlApplicationContext("beans.xml"); UserService userService=(UserService)ctx.getBean("userService"); User u=new User(); u.setUsername("u1"); u.setPassword("p1"); userService.add(u); }测试成功!
<bean id="userService" class="cn.edu.hpu.service.UserService"> <constructor-arg index="0" value="75800000"/> <constructor-arg index="1" value="42"/> </bean>用index来制定传值的顺序(类型不一样要指定type属性,如type="int")
3.接口注入:使用极少,用到再查
转载请注明出处:http://blog.csdn.net/acmman