How can we get access to ApplicationContext from a CommandLineRunner class. Is there a better newer way than using ApplicationContextAware
2 Answers
Autowiring would work, either as a field
@Autowired
private ApplicationContext context;
or a method
@Autowired
public void context(ApplicationContext context) { this.context = context; }
Same as ApplicationContextAware really.
It's a smell in any case - maybe if you think about your use case you will find a way to do it without the context?
1 Comment
adeelmahmood
Well I am dynamically creating spring integration application contexts for file:inbound-channel-adapters and the idea here is to pass the parent application context to child contexts to allow them to use beans defined in parent application contexts.
@Bean
@Autowired
public CommandLineRunner listAllBeans(ApplicationContext applicationContext) {
return new CommandLineRunner() {
@Override
public void run(String... args) throws Exception {
String[] allBeanNames = applicationContext.getBeanDefinitionNames();
System.out.println("doing listAllBeans");
for(String beanName : allBeanNames) {
System.out.println(beanName);
}
}
};
}