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();
 }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值