首页 > 代码库 > Spring接口编程_设值注入和构造注入
Spring接口编程_设值注入和构造注入
说明:
UserManagerImp是设值注入,UserManagerImp2是构造注入
接口不注入,也就是在Spring配置文件中没有接口的<bean>,但是定义的时候是用接口
private IUserDao userDao;
IUserManager userManager2=(IUserManager) factory.getBean("userManager2");
类都注入,①UserManagerImp和UserManagerImp2属于实现类
②UserDaoImp是Dao类也要注入
前者①中有属性userDao,userDao可以通过设值和构造俩中方法注入
后者②中没有属性,所以只写了<bean>
1.文件
<?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 name="userManager" class="com.wangcf.manager.UserManagerImp"> <!--设值注入 --> <property name="userDao" ref="userDao"></property> </bean> <bean name="userManager2" class="com.wangcf.manager.UserManagerImp2"> <!-- 构造注入 --> <constructor-arg ref="userDao"/> </bean> <bean name="userDao" class="com.wangcf.Dao.UserDaoImp"></bean> </beans>
2.Dao
package com.wangcf.Dao; public interface IUserDao { public void addUser(); }
package com.wangcf.Dao; public class UserDaoImp implements IUserDao{ public void addUser(){ System.out.println("UserDaoImp addUser..."); } }
3.manager
package com.wangcf.manager; public interface IUserManager { public void addUser(); }
package com.wangcf.manager; import com.wangcf.Dao.IUserDao; public class UserManagerImp implements IUserManager{ private IUserDao userDao; //设值注入 public void setUserDao(IUserDao userDao) { this.userDao = userDao; } public void addUser(){ System.out.println("UserManagerImp addUser..."); this.userDao.addUser(); } }
package com.wangcf.manager; import com.wangcf.Dao.IUserDao; public class UserManagerImp2 implements IUserManager{ private IUserDao userDao; //构造注入 public UserManagerImp2(IUserDao userDao) { // TODO Auto-generated constructor stub this.userDao=userDao; } @Override public void addUser() { // TODO Auto-generated method stub System.out.println("UserManagerImp2 addUser..."); this.userDao.addUser(); } }
4.test
package com.wangcf.test; import org.springframework.beans.factory.BeanFactory; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.wangcf.manager.IUserManager; import junit.framework.TestCase; public class UserManagerTest extends TestCase{ public void testAddUser(){ BeanFactory factory=new ClassPathXmlApplicationContext("applicationContext.xml"); IUserManager userManager=(IUserManager) factory.getBean("userManager"); userManager.addUser(); System.out.println("============="); IUserManager userManager2=(IUserManager) factory.getBean("userManager2"); userManager2.addUser(); } }
5.输出
Spring接口编程_设值注入和构造注入
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。