spring java config是否支持字段注入? field是私有的,没有setter方法

时间:2017-10-24 17:57:36

标签: spring spring-java-config

如何在通过java配置连接时在bean中注入私有的“@Autowire / @Inject”字段。如果您看到以下示例:

public class HowToGetField2ByJavaConfig {

   private Field1 field1;

   @Inject
   private Field2 field2;

   @Inject
   public HowToGetField2ByJavaConfig(Field1 field1) {
     this.field1 = field1;
   }
}

使用AppConfig

@Configuration
static class AppConfig {

  /....
  /....
  /....
  @Inject
  public HowToGetField2ByJavaConfig howToGetField2ByJavaConfig(Field1 field1) {
    HowToGetField2ByJavaConfig howToGetField2ByJavaConfig = new HowToGetField2ByJavaConfig(field1);
    //here how to inject Field2
    return howToGetField2ByJavaConfig;
  }
...

1 个答案:

答案 0 :(得分:1)

我不建议这样做,但可以做到。

Spring @Autowired尝试按名称类型注入bean。
因此,如果你想创建Beans的方式,你可以这样做:

@Configuration
@ComponentScan("nl.testing")
public class AppConfig {

  @Bean
  public Field1 field1() {
    // This will be injected inside your bean method below which creates the TooLongName bean
    return new Field1();
  }

  @Bean
  public Field2 field2() {
    // Via the `@Autowired` this will be injected in the Field of your
    // TooLongName class (this has preference because it matches the name)
    return new Field2();
  }

  @Bean
  public Field2 otherField2() {
    // This won't be used because `field2()` is prefered.
    return new Field2();
  }

  @Bean
  public TooLongName tooLongName(Field1 field1) {
    TooLongName tooLongName = new TooLongName(field1);
    return tooLongName;
  }
}