使用构造方法注入

使用构造方法注入

目录结构在这里插入图片描述

TestDiDao

package dao;

public interface TestDiDao {
    public void sayHello();
}

TestDiDaoImpl

package dao;

public class TestDiDaoImpl implements TestDiDao{
    @Override
    public void sayHello() {
        System.out.println("TestDiDao say: Hello, Study hard!");
    }
}

TestDiService

package service;

public interface TestDiService {
    public void sayHello();
}

TestDiServiceImpl

package service;

import dao.TestDiDao;
import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @User SunLionAhh
 * @Date 2020-09-07 8:38
 */

public class TestDiServiceImpl implements TestDiService{

    // @Autowired
    private final TestDiDao testDiDao;
    // 构造方法,用于实现依赖注入接口对象testDiDao
    public TestDiServiceImpl(TestDiDao testDiDao){
        super();
        this.testDiDao = testDiDao;
    }

    @Override
    public void sayHello() {
        // 调用testDiDao中的sayHello方法
        testDiDao.sayHello();
        System.out.println("TestDiService 构造方法注入 say: Hello, Study hard!");
    }
}

TestDi

package test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import service.TestDiService;

/**
 * @User SunLionAhh
 * @Date 2020-09-07 9:26
 */

public class TestDi {
    public static void main(String[] args){
        //初始化Spring容器ApplicationContext,加载配置文件
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        TestDiService testDiService = (TestDiService) applicationContext.getBean("testDiService");
        testDiService.sayHello();

    }
}

applicationContext.xml

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

    <!--将指定类TestDiDaoImpl配置给Spring,让Spring创建其实例-->
    <bean id="myTestDiDao" class="dao.TestDiDaoImpl">
        <!-- collaborators and configuration for this bean go here -->
    </bean>

    <!--使用构造方法注入-->
    <bean id="testDiService" class="service.TestDiServiceImpl">
        <!--将myTestDiDao注入到TestDiServiceImpl类的属性testDiDao上-->
        <constructor-arg index="0" ref="myTestDiDao"/>
        <!--在配置文件中,constructor-arg元素用于定义类构造方法的参数,index用于定义参数的位置,
        ref指定某个实例的引用,如果参数是常量值,ref由value代替,如:
        <constructor-arg index="1" value="41890"/>-->
    </bean>
</beans>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值