【问题标题】:init method in jersey jax-rs web servicejersey jax-rs Web 服务中的 init 方法
【发布时间】:2016-10-02 20:05:49
【问题描述】:

我是 jax-rs 的新手,并且已经使用 jersey 和 glassfish 构建了一个 Web 服务。

我需要的是一个方法,一旦服务启动就会被调用。在这个方法中,我想加载一个自定义配置文件,设置一些属性,写一个日志,等等......

我尝试使用 servlet 的构造函数,但每次调用 GET 或 POST 方法时都会调用构造函数。

我必须实现哪些选项?

请告诉我,如果需要一些依赖项,请告诉我如何将其添加到 pom.xml(或其他)

【问题讨论】:

    标签: jersey jax-rs init


    【解决方案1】:

    有多种方法可以实现它,具体取决于您的应用程序中可用的内容:

    使用来自 Servlet API 的 ServletContextListener

    一旦在 Servlet API 之上构建 JAX-RS,下面的代码就可以解决问题:

    @WebListener
    public class StartupListener implements ServletContextListener {
    
        @Override
        public void contextInitialized(ServletContextEvent event) {
            // Perform action during application's startup
        }
    
        @Override
        public void contextDestroyed(ServletContextEvent event) {
            // Perform action during application's shutdown
        }
    }
    

    使用来自 CDI 的 @ApplicationScoped@Observes

    将 JAX-RS 与 CDI 结合使用时,您可以拥有以下内容:

    @ApplicationScoped
    public class StartupListener {
    
        public void init(@Observes 
                         @Initialized(ApplicationScoped.class) ServletContext context) {
            // Perform action during application's startup
        }
    
        public void destroy(@Observes 
                            @Destroyed(ApplicationScoped.class) ServletContext context) {
            // Perform action during application's shutdown
        }
    }
    

    在这种方法中,您必须使用来自javax.enterprise.context 包的@ApplicationScoped来自javax.faces.bean 包的@ApplicationScoped

    在 EJB 中使用 @Startup@Singleton

    将 JAX-RS 与 EJB 结合使用时,您可以尝试:

    @Startup
    @Singleton
    public class StartupListener {
    
        @PostConstruct
        public void init() {
            // Perform action during application's startup
        }
    
        @PreDestroy
        public void destroy() {
            // Perform action during application's shutdown
        }
    }
    

    如果您有兴趣阅读属性文件,请查看question。如果您使用 CDI 并且愿意将 Apache DeltaSpike 依赖项添加到您的项目中,请考虑查看此 answer

    【讨论】:

    • 好的,我尝试在我的项目中使用 EJB 3.1 作为最后一个方法,添加 Startup 和 Singleton,但是当我启动服务时,不会调用 init() 方法。我错过了什么?
    • @Surras 尝试第一种方法,使用 Servlet API 中的 ServletContextListener
    • 我已经尝试了第一个,但我遇到了一个异常。我认为它的发生是因为我已经在我的 pom.xml 中使用了 jersey-servlet-container 并且我无法同时加载两者,我错了吗?
    • 好的,现在第一个工作了(我在 pom.xml 中使用了错误的依赖项)。但是如何声明可以在我的 GET 和 POST 方法中访问的变量(并且是单例的)?
    • @Surras 如何声明可在我的 GET 和 POST 方法中访问的变量 我真的不清楚。
    猜你喜欢
    • 1970-01-01
    • 2017-10-08
    • 2013-10-15
    • 2014-03-14
    • 2014-02-04
    • 2013-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多