如何在Spring DI失败时阻止Java EE应用程序启动

时间:2011-02-15 17:35:10

标签: spring exception-handling java-ee websphere

(我不确定这个问题是否适用于一般的Java EE应用程序,或者是否特定于Websphere。)

当我们在部署到WebSphere的应用程序上遇到Spring DI故障时(例如,JNDI查找失败),应用程序似乎仍然已成功启动。

[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

如果在spring初始化期间抛出异常,如何使应用程序无法启动?

2 个答案:

答案 0 :(得分:2)

检查this是否有帮助。基于此我猜它是应用程序服务器特定的,但不确定。

答案 1 :(得分:0)

将Spring上下文的生命周期与应用程序的生命周期绑定应该有所帮助。

J2EE服务器内部Spring上下文主要通过org.springframework.context.access.ContextSingletonBeanFactoryLocator获取(例如,它由org.springframework.ejb.interceptor.SpringBeanAutowiringInterceptor使用)。在应用程序启动时急切地调用Spring上下文初始化应该可以完成这项工作。

可以使用Startup Beans以WebSphere特定方式完成:


@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();
        }
    }

}

使用包含类似代码的javax.servlet.ServletContextListener添加webapp模块也可以。