Reputation: 2431
How can we get access to ApplicationContext from a CommandLineRunner class. Is there a better newer way than using ApplicationContextAware
Upvotes: 8
Views: 17501
Reputation: 1
@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);
}
}
};
}
Upvotes: 0
Reputation: 58094
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?
Upvotes: 22