简体   繁体   English

在@Configuration中提供对spring @Bean的依赖关系的正确方法

[英]Proper way of providing dependency to spring @Bean in @Configuration

In @Configuration class it is possible to create spring bean by using method with @Bean annotation 在@Configuration类中,可以通过使用带有@Bean批注的方法来创建spring bean

@Component
public class Foo {
}

public class Bar {
  private Foo foo;

  public Bar(Foo foo) {
    this.foo = foo;
  }
}

@Configuration
public class BarConfig {
  @Bean
  public Bar bar(Foo foo) {
    return new Bar(foo);
  }
}

But injecting Foo to BarConfig class and using it that way can let you create Bar as well: 但是将Foo注入BarConfig类并以这种方式使用它还可以使您创建Bar:

@Component
public class Foo {
}

public class Bar {
  private Foo foo;

  public Bar(Foo foo) {
    this.foo = foo;
  }
}

@Configuration
public class BarConfig {
  @Autowired
  private Foo foo;

  @Bean
  public Bar bar() {
    return new Bar(foo); // bar() without args
  }
}

Is there any difference, from spring perspective, between them? 从春天的角度来看,它们之间有什么区别吗? Is 2nd incorrect? 第二个错误吗? What would it break or what would not work because of it? 它会中断什么或什么行不通的?

I managed to find that with 2nd there is no visible dependency to foo from Bar but would it affect anything? 我设法找到了2nd,Bar没有对foo的可见依赖,但这会影响什么吗? Refreshing/reloading spring context would pick up the change in foo while remaking bar, wouldn't it? 刷新/重新加载spring上下文会在重新制作bar时获取foo中的更改,不是吗?

The only difference between this two types of autowiring is amount of code that has to be written. 这两种自动装配之间的唯一区别是必须编写的代码量。

I recommend you to use the first option simply because it is shorter. 我建议您仅使用第一个选项,因为它更短。

The second option is suitable in case if you have to specify @Qualifier annotation in pair with @Autowired and the been which you want to inject declared in separate configuration. 如果必须将@Qualifier注释与@Autowired以及要注入的对象一起在单独的配置中声明,则第二个选项适用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM