Reload or refresh a Spring application context inside a test method?

By design, programmatic refreshing of an ApplicationContext is not explicitly supported by the Spring TestContext Framework. Furthermore, it is not intended that a test method refresh a context. Thus I would recommend that you reassess your need for a refresh and consider alternatives like placing test methods that require a different set of active profiles … Read more

Get application context returns null

Create in onCreate() an instance of getApplicationContext() (mContext) then call MyApp.getContext() from everywhere in your app and you will get your application context statically. public class MyApp extends Application { private static Context mContext; public static Context getContext() { return mContext; } @Override public void onCreate() { super.onCreate(); mContext = getApplicationContext(); } } Remember to … Read more

Spring cannot find bean xml configuration file when it does exist

Thanks, but that was not the solution. I found it out why it wasn’t working for me. Since I’d done a declaration: ApplicationContext context = new ClassPathXmlApplicationContext(“beans.xml”); I thought I would refer to root directory of the project when beans.xml file was there. Then I put the configuration file to src/main/resources and changed initialization to: … Read more

How to add a hook to the application context initialization event?

Spring has some standard events which you can handle. To do that, you must create and register a bean that implements the ApplicationListener interface, something like this: package test.pack.age; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; public class ApplicationListenerBean implements ApplicationListener { @Override public void onApplicationEvent(ApplicationEvent event) { if (event instanceof ContextRefreshedEvent) { ApplicationContext … Read more

BeanFactory vs ApplicationContext

The spring docs are great on this: 3.8.1. BeanFactory or ApplicationContext?. They have a table with a comparison, I’ll post a snippet: Bean Factory Bean instantiation/wiring Application Context Bean instantiation/wiring Automatic BeanPostProcessor registration Automatic BeanFactoryPostProcessor registration Convenient MessageSource access (for i18n) ApplicationEvent publication So if you need any of the points presented on the Application … Read more