Spring依赖注入的魔法:深入DI的实现原理【beans 五】

简介: Spring依赖注入的魔法:深入DI的实现原理【beans 五】

欢迎来到我的博客,代码的世界里,每一行都是一个故事


前言

在软件开发的舞台上,依赖注入是一个强大的设计模式,而Spring框架以其优雅的实现而脱颖而出。你可能已经使用了DI,但你是否真正了解它的实现原理呢?在这篇文章中,我们将打开DI的黑盒,揭开Spring DI的神秘面纱,让你更深刻地理解这一关键的框架特性。

DI的基本概念

依赖注入(Dependency Injection,简称DI)是一种软件设计模式,它用于解耦组件之间的依赖关系。在依赖注入中,组件不再负责自己依赖的对象的创建和管理,而是由外部容器(通常是一个框架或容器)负责注入依赖的对象。这种注入通常通过构造函数、方法或属性进行。

基本概念:

  1. 依赖(Dependency): 表示一个对象需要另一个对象来完成特定的功能。例如,一个类可能依赖于一个数据库连接、一个服务类或其他组件。
  2. 注入(Injection): 表示将依赖关系注入到类中。这可以通过构造函数、方法参数或属性来实现。

为什么使用依赖注入:

  1. 解耦: 依赖注入有助于降低组件之间的耦合度。组件不再直接创建或管理它们的依赖关系,而是由外部容器负责。这样,组件之间的关系更加灵活,更容易修改和维护。
  2. 可测试性: 依赖注入使得组件更容易进行单元测试。因为依赖关系被注入,测试时可以使用模拟对象或桩对象替代真实的依赖,从而更容易进行单元测试。
  3. 可维护性: 通过将依赖关系的创建和管理移到外部容器中,代码变得更加清晰、简洁,并且更容易理解和维护。每个组件只需要关注自己的功能,而不必关心如何创建和管理依赖关系。
  4. 灵活性: 依赖注入提供了更大的灵活性,可以轻松更改组件之间的关系,而无需修改组件本身的代码。这使得系统更容易适应变化和演进。
  5. 可重用性: 通过将依赖关系解耦,依赖注入可以促使更多的组件变得可重用。一个组件可以在不同的上下文中使用,而不必担心它的依赖关系。

总体而言,依赖注入是一种有助于提高代码质量、可维护性和可测试性的设计模式,特别是在大型项目和团队中。它有助于创建更灵活、可扩展且易于维护的应用程序。

构造器注入

构造器注入是一种依赖注入的方式,通过构造函数来注入一个类的依赖。在Spring中,构造器注入是一种推荐的注入方式,因为它能够确保依赖在对象创建时就被满足,从而提高对象的不可变性和一致性。以下是构造器注入的基本概念和多个构造函数的处理方法。

构造器注入的基本概念:

  1. 构造函数(Constructor): 一个类的构造函数是用于创建对象的方法。在构造函数中,可以接受依赖关系所需的参数。
  2. 构造器注入(Constructor Injection): 将依赖关系通过构造函数的参数进行注入。这意味着对象在被创建时,其依赖关系必须通过构造函数提供。

示例:

public class MyService {
    private final MyDependency myDependency;
    // 构造函数注入
    public MyService(MyDependency myDependency) {
        this.myDependency = myDependency;
    }
    // 其他业务逻辑
}

在上述例子中,MyService通过构造函数接受一个MyDependency的实例,从而实现了构造器注入。

多个构造函数的处理:

如果一个类有多个构造函数,Spring会尽量通过匹配参数类型和数量的方式选择合适的构造函数。但是,在有多个构造函数的情况下,可能会出现歧义,需要通过@Autowired@Qualifier注解来明确指定使用哪个构造函数。

public class MyService {
    private final MyDependency myDependency;
    // 主要的构造函数
    @Autowired
    public MyService(MyDependency myDependency) {
        this.myDependency = myDependency;
    }
    // 辅助的构造函数
    @Autowired
    public MyService(MyDependency myDependency, OtherDependency otherDependency) {
        this.myDependency = myDependency;
        // 处理其他依赖
    }
    // 其他业务逻辑
}

在上述例子中,通过@Autowired注解标注了两个构造函数,Spring会选择匹配的构造函数来注入依赖。如果需要明确指定使用哪个构造函数,可以使用@Qualifier注解。

public class MyService {
    private final MyDependency myDependency;
    // 主要的构造函数
    @Autowired
    public MyService(@Qualifier("primaryMyDependency") MyDependency myDependency) {
        this.myDependency = myDependency;
    }
    // 辅助的构造函数
    @Autowired
    public MyService(@Qualifier("secondaryMyDependency") MyDependency myDependency) {
        this.myDependency = myDependency;
    }
    // 其他业务逻辑
}

在这个例子中,@Qualifier注解用于指定使用哪个具体的MyDependency的实例。

总的来说,构造器注入是一种简单、直观、推荐的依赖注入方式,通过构造函数接受依赖关系,使得对象的创建和初始化更加清晰和可控。在有多个构造函数的情况下,通过@Autowired@Qualifier来进行注解可以更好地处理依赖关系。

Setter方法注入

Setter方法注入是一种通过Setter方法将依赖关系注入到类中的方式。在Spring中,这是另一种常见的依赖注入方式,特别适用于那些希望在对象创建后灵活设置依赖关系的情况。以下是Setter方法注入的基本概念和可选性的Setter方法的处理方法。

Setter方法注入的基本概念:

  1. Setter方法: 一个类中的Setter方法用于设置对象的属性或依赖关系。
  2. Setter方法注入: 将依赖关系通过Setter方法进行注入。这意味着对象在创建后,通过调用相应的Setter方法来提供依赖。

示例:

public class MyService {
    private MyDependency myDependency;
    // Setter方法注入
    public void setMyDependency(MyDependency myDependency) {
        this.myDependency = myDependency;
    }
    // 其他业务逻辑
}

在上述例子中,MyService通过一个名为setMyDependency的Setter方法接受一个MyDependency的实例,从而实现了Setter方法注入。

可选性的Setter方法:

有时候,某个依赖关系可能是可选的,这时你可以通过使用@Autowired注解的required属性为Setter方法设置可选性。如果required属性设置为false,则该依赖关系是可选的,如果找不到匹配的Bean,Spring容器不会报错,而是跳过这个Setter方法的注入。

public class MyService {
    private MyDependency myDependency;
    // 可选性的Setter方法注入
    @Autowired(required = false)
    public void setMyDependency(MyDependency myDependency) {
        this.myDependency = myDependency;
    }
    // 其他业务逻辑
}

在上述例子中,setMyDependency方法被标注为可选的,如果找不到匹配的MyDependency的Bean,Spring容器不会报错。

Setter方法注入的优势在于它提供了更灵活的方式来设置依赖关系,特别适用于那些依赖关系不是必需的情况。然而,在某些情况下,Setter方法注入可能导致对象处于不完全初始化的状态,因此需要谨慎使用。

接口注入

在Spring中,你可以通过在接口中定义依赖注入的方法,然后在实现这个接口的类中实现该方法,来实现接口注入。这种方式通常用于在接口中定义一些默认的行为或配置,然后在实现类中进行具体的依赖注入。以下是一个简单的示例:

1. 定义接口:

public interface DependencyInjectable {
    void injectDependency(MyDependency myDependency);
}

在上述例子中,DependencyInjectable接口定义了一个名为injectDependency的方法,用于依赖注入。

2. 实现接口:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class MyService implements DependencyInjectable {
    private MyDependency myDependency;
    // 实现接口的依赖注入方法
    @Override
    @Autowired
    public void injectDependency(MyDependency myDependency) {
        this.myDependency = myDependency;
    }
    // 其他业务逻辑
}

在上述例子中,MyService类实现了DependencyInjectable接口,并在该类中使用@Autowired注解实现了injectDependency方法的依赖注入。

3. 使用注入后的依赖:

public class AnotherService {
    private final DependencyInjectable dependencyInjectable;
    public AnotherService(DependencyInjectable dependencyInjectable) {
        this.dependencyInjectable = dependencyInjectable;
    }
    public void performOperation() {
        // 使用注入后的依赖
        dependencyInjectable.injectDependency(new MyDependency());
        // 其他操作
    }
}

在上述例子中,AnotherService类通过构造函数注入了一个实现了DependencyInjectable接口的实例,并在performOperation方法中调用了injectDependency方法。

接口注入的主要优势在于它可以在接口中定义一些默认的行为或配置,然后在实现类中选择性地实现或覆盖这些方法。这使得接口可以在不同的实现类中具有不同的依赖注入逻辑,提供更大的灵活性。但需要注意的是,这种方式可能导致实现类对Spring的依赖,因此在使用时需要谨慎。

自动装配

在Spring中,@Autowired注解用于实现自动装配(Autowired),它可以自动将匹配类型的Bean注入到目标类的字段、构造函数或方法参数中。自动装配可以根据类型和名称进行匹配。以下是关于@Autowired注解的使用示例:

1. 根据类型进行自动装配:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class MyService {
    private final MyDependency myDependency;
    // 根据类型进行自动装配
    @Autowired
    public MyService(MyDependency myDependency) {
        this.myDependency = myDependency;
    }
    // 其他业务逻辑
}

在上述例子中,MyService类通过构造函数使用@Autowired注解自动注入了一个MyDependency类型的Bean。

2. 根据名称进行自动装配:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
@Component
public class AnotherService {
    private final MyDependency myDependency;
    // 根据名称进行自动装配
    @Autowired
    public AnotherService(@Qualifier("specificDependency") MyDependency myDependency) {
        this.myDependency = myDependency;
    }
    // 其他业务逻辑
}

在上述例子中,AnotherService类通过构造函数使用@Autowired注解自动注入了一个名为specificDependencyMyDependency类型的Bean。使用了@Qualifier注解来指定具体的Bean名称。

3. 字段和方法参数的自动装配:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
@Component
public class YetAnotherService {
    private MyDependency myDependency;
    // 字段自动装配
    @Autowired
    @Qualifier("specificDependency")
    private AnotherDependency anotherDependency;
    // 方法参数自动装配
    @Autowired
    public void setMyDependency(@Qualifier("specificDependency") MyDependency myDependency) {
        this.myDependency = myDependency;
    }
    // 其他业务逻辑
}

在上述例子中,YetAnotherService类通过字段和方法参数分别使用@Autowired注解实现了字段和方法参数的自动注入。同样使用了@Qualifier注解来指定具体的Bean名称。

@Autowired注解是Spring中最常用的自动装配注解之一,它简化了依赖注入的过程,提高了代码的可读性和可维护性。通过@Qualifier注解,你可以更精确地控制自动装配的具体Bean。

Qualifier注解

@Qualifier注解是Spring框架提供的一种用于解决多个同类型Bean自动装配问题的机制。当有多个相同类型的Bean存在于容器中,@Qualifier注解可以与@Autowired注解一起使用,通过指定Bean的名称来明确指定要注入的具体Bean。以下是一个简单的示例:

示例:

假设有两个实现了同一个接口的Bean:

public interface MyInterface {
    // 接口定义
}
import org.springframework.stereotype.Component;
@Component("beanA")
public class BeanA implements MyInterface {
    // 实现
}
import org.springframework.stereotype.Component;
@Component("beanB")
public class BeanB implements MyInterface {
    // 实现
}

然后在另一个类中进行自动装配:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
@Component
public class MyService {
    private final MyInterface myInterface;
    // 使用@Qualifier指定具体Bean的名称
    @Autowired
    public MyService(@Qualifier("beanB") MyInterface myInterface) {
        this.myInterface = myInterface;
    }
    // 其他业务逻辑
}

在上述例子中,MyService类通过构造函数使用@Autowired注解进行自动装配,而通过@Qualifier("beanB")注解明确指定了要注入的Bean的名称为"beanB"。这样,在存在多个实现了MyInterface接口的Bean时,Spring就能够根据@Qualifier注解找到特定的Bean来进行注入。

总体而言,@Qualifier注解是一个有效的工具,用于解决多个同类型Bean的自动装配问题。在使用时,需要确保指定的Bean名称与实际的Bean定义名称一致。

Primary注解

@Primary注解是Spring框架提供的一种机制,用于标记一个Bean作为首选的Bean。当有多个同类型的Bean存在于容器中,并且没有使用@Qualifier注解指定具体要注入的Bean时,Spring容器会优先选择标记了@Primary注解的Bean进行注入。这有助于解决多个同类型Bean的歧义性。

以下是一个简单的示例:

示例:

假设有两个实现了同一个接口的Bean:

public interface MyInterface {
    // 接口定义
}
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
@Component
@Primary
public class PrimaryBean implements MyInterface {
    // 实现
}
import org.springframework.stereotype.Component;
@Component
public class SecondaryBean implements MyInterface {
    // 实现
}

在上述例子中,PrimaryBean类使用了@Primary注解,标记为首选的Bean。

然后在另一个类中进行自动装配:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class MyService {
    private final MyInterface myInterface;
    // 由于PrimaryBean标记了@Primary,它会被首选注入
    @Autowired
    public MyService(MyInterface myInterface) {
        this.myInterface = myInterface;
    }
    // 其他业务逻辑
}

在上述例子中,MyService类通过构造函数使用@Autowired注解进行自动装配,由于PrimaryBean标记了@Primary注解,它会被首选注入到myInterface字段中。

总体而言,@Primary注解是一种方便的机制,用于解决多个同类型Bean的自动装配问题,使得Spring容器能够明确知道首选的Bean是哪个。需要注意的是,使用@Primary注解时,确保只在必要的情况下使用,以避免引入歧义。****

使用java配置进行DI

在Spring中,可以使用Java配置类(通过@Configuration注解标记的类)和@Bean注解来实现依赖注入。以下是一个简单的示例,演示了如何使用Java配置进行依赖注入:

1. 创建一个接口和两个实现类:

// MyInterface.java
public interface MyInterface {
    void myMethod();
}
// MyImplementationA.java
public class MyImplementationA implements MyInterface {
    @Override
    public void myMethod() {
        System.out.println("MyImplementationA");
    }
}
// MyImplementationB.java
public class MyImplementationB implements MyInterface {
    @Override
    public void myMethod() {
        System.out.println("MyImplementationB");
    }
}

2. 创建一个Java配置类:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
    @Bean
    public MyInterface myImplementationA() {
        return new MyImplementationA();
    }
    @Bean
    public MyInterface myImplementationB() {
        return new MyImplementationB();
    }
}

在上述例子中,AppConfig类使用了@Configuration注解标记为Java配置类,并通过@Bean注解定义了两个Bean,分别是myImplementationAmyImplementationB

3. 使用配置类进行依赖注入:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Component;
@Component
public class MyService {
    private final MyInterface myInterface;
    @Autowired
    public MyService(MyInterface myInterface) {
        this.myInterface = myInterface;
    }
    public void performOperation() {
        myInterface.myMethod();
    }
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        MyService myService = context.getBean(MyService.class);
        myService.performOperation();
        context.close();
    }
}

在上述例子中,MyService类通过构造函数注入了一个MyInterface类型的Bean,而这个Bean的具体实现是通过AppConfig配置类定义的。在main方法中,通过AnnotationConfigApplicationContext加载配置类,然后获取MyService的Bean并调用performOperation方法。

这样,就实现了通过Java配置进行依赖注入。这种方式使得依赖关系更清晰,同时能够充分利用Java的编程能力进行灵活的配置。

相关文章
|
17天前
|
存储 人工智能 自然语言处理
RAG 调优指南:Spring AI Alibaba 模块化 RAG 原理与使用
通过遵循以上最佳实践,可以构建一个高效、可靠的 RAG 系统,为用户提供准确和专业的回答。这些实践涵盖了从文档处理到系统配置的各个方面,能够帮助开发者构建更好的 RAG 应用。
593 114
|
29天前
|
Java 容器 Spring
什么是Spring IOC 和DI ?
IOC : 控制翻转 , 它把传统上由程序代码直接操控的对象的调用权交给容 器,通过容器来实现对象组件的装配和管理。所谓的“控制反转”概念就是对组件对象控制权的转 移,从程序代码本身转移到了外部容器。 DI : 依赖注入,在我们创建对象的过程中,把对象依赖的属性注入到我们的类中。
|
8天前
|
安全 前端开发 Java
Spring Boot 项目中触发 Circular View Path 错误的原理与解决方案
在Spring Boot开发中,**Circular View Path**错误常因视图解析与Controller路径重名引发。当视图名称(如`login`)与请求路径相同,Spring MVC无法区分,导致无限循环调用。解决方法包括:1) 明确指定视图路径,避免重名;2) 将视图文件移至子目录;3) 确保Spring Security配置与Controller路径一致。通过合理设定视图和路径,可有效避免该问题,确保系统稳定运行。
43 0
|
4月前
|
设计模式 XML Java
【23种设计模式·全精解析 | 自定义Spring框架篇】Spring核心源码分析+自定义Spring的IOC功能,依赖注入功能
本文详细介绍了Spring框架的核心功能,并通过手写自定义Spring框架的方式,深入理解了Spring的IOC(控制反转)和DI(依赖注入)功能,并且学会实际运用设计模式到真实开发中。
【23种设计模式·全精解析 | 自定义Spring框架篇】Spring核心源码分析+自定义Spring的IOC功能,依赖注入功能
|
4月前
|
存储 Java 应用服务中间件
【Spring】IoC和DI,控制反转,Bean对象的获取方式
IoC,DI,控制反转容器,Bean的基本常识,类注解@Controller,获取Bean对象的常用三种方式
101 12
|
4月前
|
NoSQL Java Redis
Spring Boot 自动配置机制:从原理到自定义
Spring Boot 的自动配置机制通过 `spring.factories` 文件和 `@EnableAutoConfiguration` 注解,根据类路径中的依赖和条件注解自动配置所需的 Bean,大大简化了开发过程。本文深入探讨了自动配置的原理、条件化配置、自定义自动配置以及实际应用案例,帮助开发者更好地理解和利用这一强大特性。
323 14
|
4月前
|
Java 数据库 数据安全/隐私保护
轻松掌握Spring依赖注入:打造你的登录验证系统
本文以轻松活泼的风格,带领读者走进Spring框架中的依赖注入和登录验证的世界。通过详细的步骤和代码示例,我们从DAO层的创建到Service层的实现,再到Spring配置文件的编写,最后通过测试类验证功能,一步步构建了一个简单的登录验证系统。文章不仅提供了实用的技术指导,还以口语化和生动的语言,让学习变得不再枯燥。
84 2
|
Java Spring 安全
在Spring Beans中的JSF
在Spring Beans中的JSF http://blog.rainer.eschen.name/2007/08/21/jsf-on-spring-beans/ 以前,我写过在混合依赖注入环境中怎样使用backing beans。
789 0
|
Java Spring 安全
在Spring Beans中的JSF
版权声明:本文为博主chszs的原创文章,未经博主允许不得转载。 https://blog.csdn.net/chszs/article/details/1769864 在Spring Beans中的JSF http://blog.rainer.eschen.name/2007/08/21/jsf-on-spring-beans/以前,我写过在混合依赖注入环境中怎样使用backing beans。
897 0
|
28天前
|
XML Java 数据库连接
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——基于 xml 的整合
本教程介绍了基于XML的MyBatis整合方式。首先在`application.yml`中配置XML路径,如`classpath:mapper/*.xml`,然后创建`UserMapper.xml`文件定义SQL映射,包括`resultMap`和查询语句。通过设置`namespace`关联Mapper接口,实现如`getUserByName`的方法。Controller层调用Service完成测试,访问`/getUserByName/{name}`即可返回用户信息。为简化Mapper扫描,推荐在Spring Boot启动类用`@MapperScan`注解指定包路径避免逐个添加`@Mapper`
51 0