[英]Accessing public property of a @Lazy initialized @Bean with @PropertySource
春季4.3.12
我正在使用@Configuration類來延遲初始化bean
@Configuration
public class Configuration {
@Bean
@Lazy
public Config config(){
propertySourceInjector().injectToEnvironment();
return new Config();
}
@Bean
public PropertySourceInjector propertySourceInjector(){
return new PropertySourceInjector ();
}
}
配置類:
public class Config{
@Autowired
private Environment environment;
@Value("${customConfigValue}")
public Integer configValue;
public Integer getConfigValue() {
return configValue;
}
}
PropertySourceInjector類:
public class PropertySourceInjector {
public void injectToEnvironment(){
//reads DB and adds a property source to Spring Enviroment's property sources
}
}
當我訪問Config.getValue()方法時,注入正確發生。 添加了PropertySource,並且@Value將正確的值分配給configValue
字段。
@Autowired @Lazy
Config config;
System.out.println(Config.getConfigValue()); //works!!
當我訪問Config.value公共字段時,不會發生注入。 Bean未初始化。
@Autowired @Lazy
Config config;
System.out.println(Config.configValue) //Fails. Prints null
為什么?
Config.configValue
是對字段的直接訪問。 延遲代理不執行直接訪問的任何操作,因此沒有觸發Bean加載的操作。
將configValue
為私有字段並使用吸氣劑。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.