与 Spring Web 应用程序中的 ServletContextListener 使用不一致

问题描述 投票:0回答:0

我有一个 Spring Web 应用程序,我正在其中实现一个 ServletContextListener。我在 contextInitialized 方法中设置了一个静态 JxBrowser 引擎对象,并在 contextDestroyed 方法中将其设置为 null。在 servlet 上下文中设置的这个变量在另一个类中用于创建浏览器对象,然后再使用它以无头模式呈现 html 内容。

它工作了一段时间,然后开始给出 InvocationTargetException。作为临时修复,我重新部署了再次创建引擎对象并将其存储在 Servlet 上下文中的应用程序。

我想问一下,在 ServletContext 中设置某些东西是否随着时间的推移表现不一致。

这是示例代码

@WebListener
public class SampleContextListener implements ServletContextListener {
    public static final Logger LOGGER = LogManager.getRootLogger();
    public static Engine engine = null;
    public static ServletContext context;
    public static String browserDirectory = "/tmp";

    @Override
    public void contextInitialized(ServletContextEvent event) {
                 
        engine = Engine.newInstance(EngineOptions.newBuilder(HARDWARE_ACCELERATED)
                .licenseKey("")
                .chromiumDir(Paths.get(browserDirectory))
                .build());
        LOGGER.info("Engine Initialized => " + engine);
        context = event.getServletContext();
        context.setAttribute("engine",engine);
        
    }
    //Run this before web application is destroyed
    @Override
    public void contextDestroyed(ServletContextEvent event) {
   
        try {
            context = null;
            if(engine != null && !engine.isClosed()) {
                engine.close();
                LOGGER.info("Engine Closed => " + engine);
            }
        } catch (IOException e) {
            LOGGER.info("Error While Deleting Browser Files: " + e.getMessage());
        }
    }
}



public class TestClass {
    
    public static final Logger LOGGER = LogManager.getRootLogger();
    public static final String TMP_DIRECTORY = "/tmp"
    
    public static String getEngine() {
        
        Engine engine = null;
        Browser browser = null;
        ServletContext servletContext = SampleContextListener.context;
        engine = (Engine) servletContext.getAttribute("engine");
        Browser browser = engine.newBrowser();
    }
}
spring jakarta-ee jxbrowser servletcontextlistener
© www.soinside.com 2019 - 2024. All rights reserved.