Spring 控制反转和依赖注入

本文深入探讨了Spring框架的核心概念,包括控制反转和依赖注入的基本原理。解释了Spring如何通过定位、加载和注册Bean来简化Java应用的开发,以及如何自动化处理Bean的生命周期和依赖关系。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自从用了Spring,就一直再说控制反转(Inversion of Control)和依赖注入(dependency injection)。到底什么是控制反转,什么是依赖注入呢?

我的理解是:控制反转就是把Bean的创建权交给了Spring容器,由Spring容器去new对象,而不是我们手动去new对象。依赖注入就是当一个Bean需要另一个Bean的时候,通过一种解耦或是松耦合的方式从Spring容器中拿到Bean并组合成功能更强大,更丰富的Bean。

Spring加载Bean的三个主要步骤:定位、加载、注册

  • 定位:找到配置Bean的地方,以前都是配置在xml文件中,现在都是通过注解的方式。
  • 加载:解析xml文件,包括Bean信息和Bean之间的依赖关系
  • 注册:解析出来的Bean注册到容器中,也就是注册到IOC容器中
package com.gaohx.springbootdocker.web;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

@ComponentScan(basePackages = "com.gaohx.springbootdocker.web")
public class MySpringApplication {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MySpringApplication.class);
        DemoController demoController = context.getBean(DemoController.class);
        demoController.hello();
        context.close();
    }
}

@Controller
class DemoController{
    private DemoService demoService;
    public DemoController(DemoService demoService){
        this.demoService = demoService;
    }
    public void hello(){
        demoService.hello();
    }
}

@Service
class DemoService{
    public void hello(){
        System.out.println("hello");
    }
}

启动Main方法,看控制台,会有如下日志输出

Creating shared instance of singleton bean 'mySpringApplication'
Creating shared instance of singleton bean 'demoController'
Creating shared instance of singleton bean 'demoService'
Autowiring by type from bean name 'demoController' via constructor to bean named 'demoService'

Spring启动的时候,会自动创建我们定义好的Bean,并自动注入Bean之间的依赖关系。当Spring启动成功,所有Bean和Bean之间的依赖关系都已创建成功。我们不再需要关心Bean的生命周期及它们之间复杂的依赖关系。完全由容器处理。

想想如果手动维护这些Bean和Bean之间的依赖关系,那将是多么恐怖的事情。

以上只是对Spring简单的理解。以后有心得了再补充。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值