Extreme Java When vanilla Java is not enough

17Mar/090

Spring injection outside application context

Are you using ApplicationContext (and friends) to create a single "spring context" for all your web application? If so, you are on the right way. And it is possible that you feel the need to inject properties where Spring isn't accessible (like a Servlet Filter). You can use this little trick:

public static void inject(ServletContext context,
    Object bean) {
  WebApplicationContext wCtx =
      WebApplicationContextUtils
          .getWebApplicationContext(context);
  if (wCtx != null) {
    wCtx.getAutowireCapableBeanFactory()
        .autowireBeanProperties(bean,
            AutowireCapableBeanFactory.AUTOWIRE_NO,
            false);
  }
}