【问题标题】:Autowiring in Spring repository when created with new keyword使用新关键字创建时在 Spring 存储库中自动装配
【发布时间】:2020-11-24 17:04:55
【问题描述】:

我有如下服务

@Service
public class A {
     public B data() {
           InterfaceA B = (codition) ? new B1() : new B2();
           B.check();
     }
}

@Service
public class B1 {
     
     @Autowired
     private B1Repo b1repo;//repository

     public B1 check() {
           b1repo.find();
     }
}

当我运行服务A.data() 进程时,我将b1repo 设为空。由于我使用的是 new 关键字,因此存储库不是自动装配的。 我已经检查了以下问题 related_issue

但它并没有帮助我解决问题

【问题讨论】:

  • 您将其设为 null 是因为您正在创建自己的对象(使用 new),而不是使用使用 @Service 类创建的 DI 对象。您必须在 A 类中为 B1 使用 Autowire。
  • 你能根据你的评论更新上面的代码吗?我不知道如何在 DI 中注入服务

标签: java spring-boot autowired


【解决方案1】:

Spring Framework 自己创建所有组件实例并填充所有必需的自动连接属性。这称为依赖注入。 当您创建服务类的新实例时,它是一个没有自动连接的原始实例。

如果您必须在某些条件下实现服务,我建议使用Spring Profiles

【讨论】:

    【解决方案2】:
    @Service
    public class A {
        @Autowired
        private B1 b1;
    
        @Autowired
        private B2 b2;
    
        public B data() {
            InterfaceA B = (codition) ? b1 : b2;
            B.check();
       }
    }
    
    @Service
    public class B1 {
         
         @Autowired
         private B1Repo b1repo;//repository
    
         public B1 check() {
               b1repo.find();
         }
    }
    

    当你在 spring boot 中应用 D 的 SOLID 原则 - 依赖倒置原则时。这可能会对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2012-06-15
      • 2015-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-22
      • 2017-09-01
      • 1970-01-01
      相关资源
      最近更新 更多