9

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

2 Answers 2

22

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?

Sign up to request clarification or add additional context in comments.

1 Comment

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.
0
  @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);
            }
        }
     };
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.