【问题标题】:Spring: how to initialize a property without constructor?Spring:如何在没有构造函数的情况下初始化属性?
【发布时间】:2017-08-09 14:51:24
【问题描述】:

我有一个配置了构造函数的旧类

public class Outer
{
  ...
  public Outer(OldService oldService) { this.oldService = oldService;}
}

我需要使用新服务添加新字段,但无法更改构造函数(太多旧代码依赖它)。所以,我想得到类似的东西

public class Outer
{
  private NewService newService; // Need injection here
  public Outer(OldService oldService) { this.oldService = oldService;}
}

@Component
public class NewService
{
    public NewService(Dependency dependency){this.dependency = dependency;}
}

我尝试为 Outer.newService 应用 @Autowired 和 @Inject 属性,但没有帮助。我可以创建 Outer.Initiate(NewService newService) 方法,但这会给已经闻到的项目添加一些垃圾。

那么,我可以在 Spring 中注入字段吗?

Upd1 现在手动执行外部构造函数(如 var outer = new outer(service);)。

【问题讨论】:

  • 如果你有很多遗留代码直接调用旧的构造函数,你希望遗留代码如何填充newService 字段?
  • 您的 Outer 类需要是 Spring 组件。否则,自动装配将不起作用。
  • 如果你想要一个新的必需的NewService,你不会也破坏你的旧代码。为什么不使用构造函数(OldService oldService, NewService newService) { super(oldService); } 扩展类OuterNewOuter
  • @Juan 我已经尝试为字段应用 Autowired,为类应用组件 - newService 为空。约翰,我想即使手动调用构造函数,Spring DI 容器也会填充 newService。我错了吗?
  • 不,它不会那样工作,因为您正在创建一个实例而不是使用 Spring Bean。您应该像这样创建一个@Bean@Bean public Outer outer(){ return new Outer(oldService); } 然后您可以使用@Autowired 来获取该bean,其余的由Spring 完成。

标签: java spring


【解决方案1】:

由于 Outer.class 不是由 Spring 容器实例化而是由 new 实例化的,因此 Spring 容器无法知道它。这就是为什么 Spring 无法为 NewService 执行依赖注入。

现在,如果您将 Outer 实例化给 Spring,除了自动连接 NewService 之外,您还需要自动连接或使用任何弹簧连接将 OldService 连接到 Outer

【讨论】:

    【解决方案2】:

    您可以使用字段级注入:

    public class Outer{
      @Autowired
      private NewService newService; 
      public Outer(OldService oldService) { this.oldService = oldService;}
    }
    

    我不喜欢这种方法,因为它使测试变得更加麻烦并且隐藏了依赖关系。

    而不是这个,只需使用一个 setter 并用 Autowired 注释它,它做同样的事情:

    public class Outer{
      private NewService newService; 
      public Outer(OldService oldService) { this.oldService = oldService;}
    
      @Autowired
      public setNewService(NewService newService){
        this.newService = newService;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-01-03
      • 1970-01-01
      • 1970-01-01
      • 2022-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多