开发者

How to prevent a Java EE app from starting when Spring DI fails

开发者 https://www.devze.com 2023-02-11 03:41 出处:网络
(I\'m not sure if this question appli开发者_如何学JAVAes to Java EE apps in general or is Websphere-specific.)

(I'm not sure if this question appli开发者_如何学JAVAes to Java EE apps in general or is Websphere-specific.)

When we get a Spring DI failure on apps we've deployed to WebSphere (a JNDI lookup failure, for example) the application still appears to have started successfully.

[15/02/11 17:21:22:495 GMT] 00000037 ContextLoader E org.springframework.web.context.ContextLoader initWebApplicationContext Context initialization failed
                                 org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mybean' defined in
   ...big stack trace...
[15/02/11 17:21:22:526 GMT] 00000037 ApplicationMg A   WSVR0221I: Application started: myapp

How can I make the application fail to start if exceptions are thrown during the spring initialisation?


Check if this helps. Based on that I'd guess it's application server-specific, but not sure.


Binding Spring context's lifecycle with an application's lifecycle should help.

Inside J2EE server Spring context is acquired mostly through the org.springframework.context.access.ContextSingletonBeanFactoryLocator (for example it is used by org.springframework.ejb.interceptor.SpringBeanAutowiringInterceptor). Invoking Spring context initialization eagerly on the application startup should do the job.

It could be done in the WebSphere specific way using Startup Beans:


@RemoteHome(AppStartUpHome.class)
@Stateless
public class SpringLifecycleBean {
    private static Log logger = LogFactory.getLog(SpringLifecycleBean.class);
    private static BeanFactoryReference bfr;

    public boolean start() throws RemoteException {
        logger.debug("Initializing spring context.");

        try {
            BeanFactoryLocator bfl = ContextSingletonBeanFactoryLocator.getInstance();
            //hardcoded spring context's name (refactor for more complex use cases)
            bfr = bfl.useBeanFactory("appContext");
        } catch (Exception e) {
            logger.error("Spring context startup failed", e);
            return false;
        }

        return true;
    }

    public void stop() throws RemoteException {
        if (bfr != null) {
            logger.debug("Releasing spring context.");
            bfr.release();
        }
    }

}

Adding a webapp module with javax.servlet.ServletContextListener containing similar code will also work.

0

精彩评论

暂无评论...
验证码 换一张
取 消