spring java 配置是否支持字段注入?其中字段是私有的并且没有 setter 方法
Does spring java config support field injection? where field is private and has no setter method
如何在通过 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;
}
...
我不建议这样做,但可以做到。
Spring @Autowired
尝试通过 Name 和 Type.
注入 bean
所以如果你想按照你的要求创建 Bean,你可以这样做:
@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;
}
}
如何在通过 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;
}
...
我不建议这样做,但可以做到。
Spring @Autowired
尝试通过 Name 和 Type.
注入 bean
所以如果你想按照你的要求创建 Bean,你可以这样做:
@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;
}
}