spring依赖注入之构造器形式注入
spring依赖注入之构造器方式注入
Spring2.5的注入依赖(DI)主要有三种注入方式,即构造器注入、Setter注入和使用注解方式;注入依赖可以分为手工装配和自动装配,spring开发团队建议使用手工装配。
今天主要说说构造器注入
基于构造器的DI通过调用带参数的构造器来实现,每个参数代表着一个依赖。
1. 持久层 ,spring是基于接口编程的,请注意接口
public class StudentDao implements IStudentDao { public void saveStudent() { System.out.println("成功保存一个学生信息"); } }
2. 服务层
public class StudentService implements IStudentService { private IStudentDao studentDao; private String id; public StudentService(IStudentDao studentDao,String id){ this.studentDao = studentDao; this.id = id; } public void saveStudent() { studentDao.saveStudent(); System.out.print(",ID为:"+id); } }
3. spring配置
<bean id="studentDao" class="com.wch.dao.impl.StudentDao"></bean> <bean id="studentService" class="com.wch.service.impl.StudentService"> <constructor-arg index="0" type="com.wch.dao.IStudentDao" ref="studentDao" /> <constructor-arg index="1" value="123456" type="java.lang.String"></constructor-arg> </bean>
注:
用'type'
属性来显式指定那些构造参数的类型
index属性来显式指定构造参数的索引,从0开始
4. 经行测试,代码如下
public class TestSpringBuild extends TestCase{ private AbstractApplicationContext ctx = null; @Before public void setUp() throws Exception { //ctx = new ClassPathXmlApplicationContext("bean.xml"); ctx = new FileSystemXmlApplicationContext("classpath:bean.xml"); } @After public void tearDown() throws Exception { ctx.close(); } @Test public void testBuild(){ StudentService studentService = (StudentService)ctx.getBean("studentService"); studentService.saveStudent(); } }