In response to the answer provided by @Ashish Chaurasia, would like to mention that the solution is partial. The class ApplicationContextUtils
should also be a spring bean in order for spring to invoke the below code.
if (bean instanceof ApplicationContextAware) {
((ApplicationContextAware) bean).setApplicationContext(ctx);
}
@Component
at the top of the class would make the solution complete. Also, there is one more alternative of doing it with the @Autowired
annotation.
@Component
public class ApplicationContextProvider {
private static ApplicationContext context;
public static ApplicationContext getApplicationContext() {
return context;
}
@Autowired
public void setContext(ApplicationContext context) {
ApplicationContextProvider.context = context;
}
}
The getBean
method can now easily be accessed by -
ApplicationContextProvider.getApplicationContext().getBean("myBean");