Spring Boot ApplicationContext
The primary job of the ApplicationContext is to manage beans.
let’s create a configuration class to define our AccountService class as a Spring bean:
@Configuration public class AccountConfig { @Bean public AccountService accountService() { return new AccountService(accountRepository()); } @Bean public AccountRepository accountRepository() { return new AccountRepository(); } }
Java configuration typically uses @Bean-annotated
methods within a @Configuration
class. The @Bean
annotation on a method indicates that the method creates a Spring bean. Moreover, a class annotated with @Configuration
indicates that it contains Spring bean configurations.
AnnotationConfigApplicationContext
ApplicationContext context = new AnnotationConfigApplicationContext(AccountConfig.class); AccountService accountService = context.getBean(AccountService.class);
AnnotationConfigWebApplicationContext
is a web-based variant of AnnotationConfigApplicationContext.
We may use this class when we configure Spring’s ContextLoaderListener servlet listener or a Spring MVC DispatcherServlet in a web.xml file.
Moreover, from Spring 3.0 onward, we can also configure this application context container programmatically. All we need to do is implement the WebApplicationInitializer interface:
public class MyWebApplicationInitializer implements WebApplicationInitializer { public void onStartup(ServletContext container) throws ServletException { AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); context.register(AccountConfig.class); context.setServletContext(container); // servlet configuration } }
@Autowire ApplicationContext
You can Autowire the ApplicationContext, either as a field
@Autowired private ApplicationContext context;
or a method
@Autowired public void context(ApplicationContext context) { this.context = context; }
Finally use
context.getBean(SomeClass.class)
References
https://www.baeldung.com/spring-application-context
https://stackoverflow.com/questions/34088780/how-to-get-bean-using-application-context-in-spring-boot