Spring Boot 的构造器注入是一种常用的依赖注入方式,通过构造方法来注入依赖对象。以下是使用构造器注入的步骤:

  1. 在需要注入依赖对象的类中,定义一个构造器,参数为需要注入的依赖对象。
public class MyClass {
    private Dependency dependency;

    public MyClass(Dependency dependency) {
        this.dependency = dependency;
    }

    // ...
}
  1. 在 Spring Boot 的配置类中,通过 @Bean 注解将需要注入的依赖对象实例化,并作为构造器参数传递给需要注入的类。
@Configuration
public class AppConfig {
    @Bean
    public Dependency dependency() {
        return new Dependency();
    }

    @Bean
    public MyClass myClass(Dependency dependency) {
        return new MyClass(dependency);
    }
}
  1. 现在,当 Spring Boot 启动时,会自动将 Dependency 对象实例化,并将其传递给 MyClass 的构造器。

注意事项:

  • 确保 Dependency 类上没有其他的构造器,否则可能会导致无法正确注入依赖对象。
  • 确保 Dependency 类被 Spring Boot 的组件扫描机制识别到,例如通过 @ComponentScan 注解或在配置类中使用 @Import 注解导入。
Spring Boot 构造器注入:详解及最佳实践

原文地址: https://www.cveoy.top/t/topic/hQvA 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录