smrithishenoy
smrithishenoy

Reputation: 11

How to access ApplicationContext in Spring Boot main method?

I am just learning Spring Boot. I am creating standalone Spring Boot applications. I want to retrieve beans using applicationContext.getBean("myGreetService"). I’m doing this for learning purposes only. This is not for real-time project.

I want to retrieve the ApplicationContext in the main() method of Spring Boot application. What codes are available to get the applicationContext in the main() method?

This is what I have so far and I need codes for filling in the blanks.

@SpringBootApplication
public class DemoBootApplication {

   public static void main(String[] args) {
      SpringApplication.run(DemoBootApplication.class, args);

      // how can I access the application context here?
      // i want to do:  GreetService myService = applicationContext.getBean("myGreetService");

   }

}

I am using Spring Boot 2.6 and IntelliJ 2021.2.3.

Upvotes: 1

Views: 2245

Answers (2)

Maciej Walkowiak
Maciej Walkowiak

Reputation: 12932

SpringApplication#run returns application context, so you can do:

@SpringBootApplication
public class DemoBootApplication {

   public static void main(String[] args) {
      ApplicationContext ctx = SpringApplication.run(DemoBootApplication.class, args);

      ctx.getBean("myGreetService");
   }
}

But this is not an idiomatic way to do things in Spring. If you just want to run some piece of code after application startup, use ApplicationRunner:

@SpringBootApplication
public class DemoBootApplication {

   public static void main(String[] args) {
      SpringApplication.run(DemoBootApplication.class, args);
   }

    @Bean
    ApplicationRunner applicationRunner(MyService myService) {
        return args -> {
            System.out.println(myService);
        };
    }
}

Upvotes: 5

JRichardsz
JRichardsz

Reputation: 16505

You just need to inject the ApplicationContext

@Autowired
private ApplicationContext context;

On any bean/component of your spring boot application, including the entrypoint class itself.

Check this:

Upvotes: 0

Related Questions