當比方說,我有一個需要的值一個bean被注入到其字段之一:如何強制春先運行BeanFactoryPostProcessor的使用@Conditional
@Component
@PropertySource("classpath:spring-files/my-values.properties")
public class MyArbitraryClass implements ArbitraryClass {
@Value("#{'${values.in.property.file}'.split(',')}")
private List<String> values;
private boolean myBoolean;
@PostConstruct
private void determineBoolean() {
for (String value : values)
if (System.getProperty("whatever").contains(value))
myBoolean = true;
}
@Override
public boolean getMyBoolean() {
return myBoolean;
}
}
我想用determineBoolean()方法作爲實例化另一個bean的條件。所以,我實現了Condition接口:
public class MyCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return context.getBeanFactory().getBean(ArbitraryClass.class).getMyBoolean();
}
}
我componentScan MyArbitraryClass,以確保它實例化第一(與聲明的JavaConfig文件中的bean定義):
@Configuration
@ComponentScan("com.package.that.contains.my.arbitrary.class")
public class Conf {
@Bean
@Conditional(MyCondition.class)
// the bean type doesn't really matter
Reader reader() throws FileNotFoundException {
return new FileReader(new File(""));
}
@Bean
static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
注入價值當MyCondition評估時,MyArbitraryClass中的'values'字段將爲null。我敢肯定,這是因爲注入MyCondition中的matches()方法的應用程序上下文包含(當時)在之前的bean ,它們由BeanFactoryPostProcessors(在本例中爲PropertySourcesPlaceHolderConfigurer)處理。
有沒有辦法在處理完match()方法後獲取bean的方法,並將所有值注入到它中?
很好的建議。現在正在工作,謝謝。 – Ozilophile