java ee后台服务

jer*_*luc 4 java servlets jakarta-ee

如果我描述得不正确,你将不得不原谅我,但本质上我试图让一个类似服务的类在服务器启动时只实例化一次,并在后台“存在”直到它被杀死在服务器停止时关闭。至少据我所知,这与典型的 servlet 并不完全相同(尽管我对此可能有误)。更重要的是,我还需要能够稍后访问此服务/对象。

例如,在我参与的另一个项目中,我们使用 Spring 框架来完成类似的工作。本质上,我们使用配置 XML 文件和内置注解让 Spring 知道实例化我们一些服务的实例。后来,我们使用注释@Autowired 来“抓取”这个预先实例化的服务/对象的对象引用。

因此,尽管它似乎与 Java 本身的一些主要概念相悖,但我只是想弄清楚如何在这里重新发明这个轮子。我想有时我觉得这些大型应用程序框架在幕后做了太多的“黑盒魔术”,我真的很想能够进行微调。

感谢您的任何帮助和/或建议!


哦,我正在尝试从 JBoss 6 运行这一切

Whi*_*g34 5

这是一种方法。将 servlet 上下文侦听器添加到您的web.xml,例如:

<listener>
    <listener-class>com.example.BackgroundServletContextListener</listener-class>
</listener>
Run Code Online (Sandbox Code Playgroud)

然后创建该类来管理您的后台服务。在这个例子中,我使用单线程ScheduledExecutorService来安排它每 5 分钟运行一次:

public class BackgroundServletContextListener implements ServletContextListener {
    private ScheduledExecutorService executor;
    private BackgroundService service;

    public void contextInitialized(ServletContextEvent sce) {
        service = new BackgroundService();

        // setup single thread to run background service every 5 minutes
        executor = Executors.newSingleThreadScheduledExecutor();
        executor.scheduleAtFixedRate(service, 0, 5, TimeUnit.MINUTES);

        // make the background service available to the servlet context
        sce.getServletContext().setAttribute("service", service);
    }

    public void contextDestroyed(ServletContextEvent sce) {
        executor.shutdown();
    }
}

public class BackgroundService implements Runnable {
    public void run() {
        // do your background processing here
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您需要访问BackgroundService来自 Web 的请求,您可以通过ServletContext. 例如:

ServletContext context = request.getSession().getServletContext();
BackgroundService service = (BackgroundService) context.getAttribute("service");
Run Code Online (Sandbox Code Playgroud)