adeelmahmood
adeelmahmood

Reputation: 2431

Getting application context from a CommandLinerRunner

How can we get access to ApplicationContext from a CommandLineRunner class. Is there a better newer way than using ApplicationContextAware

Upvotes: 8

Views: 17501

Answers (2)

Amit Kumar
Amit Kumar

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

Dave Syer
Dave Syer

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

Related Questions