粗浅理解依赖注入

粗浅理解依赖注入

1 先明确一个知识点,没有初始化的对象能用吗?

class A{
    public A(){}
    public void test(){
        System.out.println("能输出吗?");
    }
}

public class DIdemo {
    public static void main(String[] args) {
        //没有初始化的对象
        A me;
        me.test();
    }
}

明显是不能用的,IDEA报错

Wrong:

Variable ‘me’ might not have been initialized

接下来我们分析一个依赖注入的最简单的模板

HelloDao类

public class HelloDao {
    public void insert(){
        System.out.println("Hello,This is insert");
    }
}

HelloDemo类

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

public class HelloDemo {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("../../../applicationContext.xml",HelloDemo.class);
        HelloService helloService= (HelloService) context.getBean("helloService");
        helloService.sayHello();
    }
}

HelloService类

public class HelloService {
    private String name;
    private HelloDao helloDao;
    //这里是构造器注入
    public HelloService(String name) {
        this.name = name;
    }
    //这里是设置值注入(也可以理解为setter方法注入)
    public void setHelloDao(HelloDao helloDao) {
        this.helloDao = helloDao;
    }
    public HelloDao getHelloDao() {
        return helloDao;
    }
    public void sayHello() {
        System.out.println("hello" + this.name);
        helloDao.insert();
    }
}

分析:

这里的JavaBean,是HelloDao这个类。HelloService依赖于HelloDao。在HelloService当中,name属性和helloDao都被private封死了,无法对其进行初始化,那怎么办呢?

举个例子啊,你是个刺客,你有个任务:毒死暴戾的皇帝,现在给你个西瓜(对应封装好的类),和一针筒毒药,要求你将这个西瓜变毒(对应给这个西瓜的属性/对象初始化),还不破坏它,那就要进行注射了

private将HelloService类的属性封死了,封死了自然而然就不能通过外界赋值初始化了嘛。我们就要利用Spring的IoC容器这个针筒对HelloService类的属性赋值初始化

以上分析帮助你理解,现在看点直观的

​ 以下是创建“针筒”的XML文件,是Spring的配置文件

<?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对象-->
    <bean id="helloDao" class="com.example.demo3.HelloDao"/>
    <!-- 用户服务 -->
    <bean id="helloService" class="com.example.demo3.HelloService">
        <!--Spring的两大注入方法之一:构造器注入-->
        <constructor-arg name="name" value="Spring IoC Container"/>
        <!--Spring的两大注入方法之二:设置值注入-->
        <property name="helloDao" ref="helloDao"/>
    </bean>
</beans>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

李南想做条咸鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值