Saturday, August 20, 2016

Autowire beans to a non-bean object in Spring framework

To autowire beans to a non-bean object in Spring framework, do as follows:

@Autowired
private ApplicationContext applicationContext;

@Bean
public List<AnswerEngine> answerEngines() {
AutowireCapableBeanFactory factory =
this.applicationContext.getAutowireCapableBeanFactory();
List<AppProperties.AnswerEngineSpec> answerEngineSpecs =
this.properties.getAnswerEngineSpecs();
Collections.sort(
answerEngineSpecs,
(o1, o2) -> Integer.compare(o1.getEngineOrder(), o2.getEngineOrder()));
List<AnswerEngine> answerEngines = new ArrayList<>();
for (AppProperties.AnswerEngineSpec spec : answerEngineSpecs) {
AnswerEngine answerEngine =
(AnswerEngine) ClassUtils.createInstance(spec.getEngineClass());
factory.autowireBean(answerEngine);
answerEngines.add(answerEngine);
}
return answerEngines;
}

Note that getting `AutowireCapableBeanFactory` from `ApplicationContext` and invoking `autowireBean()`.

No comments:

Post a Comment