依赖注入,setter方法注入

Spring框架的依赖注入通常有两种实现方式,一种是使用构造方法注入,另一种是使用属性的setter方法注入,这里是setter方法注入;

目录结构:

1.  创建com.DI 包,并在包中创建TestDIDao 接口,和接口实现类TestDIDaoImpl;

TestDIDao 接口:

package com.DI;

public interface TestDIDao {
    public void sayHello();
}

接口实现类TestDIDaoImpl:

package com.DI;

public class TestDIDaoImpl implements TestDIDao {
    public void sayHello(){
        System.out.println("TestDIDao");
    }
}

2. 创建service包,并在包中创建 TestDIService 接口和接口的是实现类 TestDIServiceImpl;

TestDIService 接口:

package com.service;

public interface TestDIService {
    public void sayHello();
}

接口的是实现类 TestDIServiceImpl:

在 TestDIServiceImpl 中使用属性的 setter 方法依赖注入 TestDIDao 接口对象;

package com.service;

import com.DI.TestDIDao;

public class TestDIServiceImpl implements TestDIService{

    private TestDIDao testDIDao;
    //添加testDIDao属性的setter方法,用于实现依赖注入
    public void setTestDIDao(TestDIDao testDIDao){
        this.testDIDao=testDIDao;
    }

    public void sayHello() {
        //调用testDIDao中的sayHello方法
        testDIDao.sayHello();
        System.out.println("setter方法注入");
    }
}

3. 编写配置文件 applicationContext.xml ;

将 TestDIServiceImpl 类托管给Spring,让Spring 创建其对象,同时调用 TestDIServiceImpl 类的

setter 方法完成依赖注入。

<?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.xsd">

    <bean id="myTestDIDao" class="com.DI.TestDIDaoImpl"/>
    <!-- 使用setter方法注入 -->
    <bean id="testDIService" class="com.service.TestDIServiceImpl">
        <!-- 调用 TestDIServiceImpl 类的setter 方法将myTestDIDao注入到
             TestDIServiceImpl 类的属性 testDIDao上 -->
        <property name="testDIDao" ref="myTestDIDao"/>
    </bean>

</beans>

4. 创建 test 包,并创建TestDI 测试类;

package com.test;

import com.service.TestDIService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestDI {
    public static void main(String[] args) {
        //初始化Spring容器,加载配置文件
        ApplicationContext applicationContext =
                new ClassPathXmlApplicationContext ("applicationContext.xml");
        //通过容器获取testDIService 实例,测试setter方法注入
        TestDIService ts = (TestDIService) applicationContext.getBean("testDIService");
        ts.sayHello();
    }
}

5. 执行测试类;

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值