后端与系统架构440 字

依赖注入

·全库 380 / 611

《依赖注入》共 0.0 万字,归在「后端与系统架构」这一层。

适合给 AI 系统搭底座、要管得住的人

目录骨架(4 节)
  1. 3.1 Spring中的构造器注入
  2. 3.2 Spring中的Setter方法注入
  3. 3.3 Spring中的字段注入
  4. 示例代码
目录 · 6 节

依赖注入(Dependency Injection, DI)是软件开发中的一种设计模式,它可以使代码更加松耦合、便于测试和维护。在Java开发中,尤其是在Spring框架中,依赖注入扮演着非常重要的角色。

1. 什么是依赖注入

依赖注入是一种设计模式,其核心思想是将对象的创建和对其依赖的管理交给外部容器,而不是在内部进行管理。这促进了松耦合,使得代码更易于测试和维护。

2. 依赖注入的三种方式

  • 构造器注入: 通过构造函数提供依赖对象。
  • Setter方法注入: 通过Setter方法提供依赖对象。
  • 字段注入: 通过属性字段提供依赖对象。

3. Spring中的依赖注入

Spring框架是Java领域最著名的依赖注入框架。它通过配置文件或注解配置来管理对象的生命周期和依赖关系。

3.1 Spring中的构造器注入

示例代码

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

@Component
class ServiceA {
    // Service implementation
}
@Component
class ServiceB {
    private  ServiceA serviceA;
    @Autowired
    public ServiceB(ServiceA serviceA) {
        this.serviceA = serviceA;
    }
    public void performTask() {
        // Use serviceA to perform some task
        System.out.println(this.serviceA);
    }
}

3.2 Spring中的Setter方法注入

示例代码

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
@Component
class ServiceA {
    // Service implementation
}
@Component
class ServiceB {
    private ServiceA serviceA;
    @Autowired
    public void setServiceA(ServiceA serviceA) {
        this.serviceA = serviceA;
    }
    public void performTask() {
        // Use serviceA to perform some task
        System.out.println(this.serviceA);
    }
}

3.3 Spring中的字段注入

示例代码

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
@Component
class ServiceA {
    // Service implementation
}
@Component
class ServiceB {
    @Autowired
    private ServiceA serviceA;
    public void performTask() {
        // Use serviceA to perform some task
        System.out.println(this.serviceA);
    }
}

资料里没有你的场景?

把你手上的数据和想解决的那个环节发上来,我们按具体情况回,不复述方法论。

发布需求