如何在通过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;
}
...
答案 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;
}
}