gpt4 book ai didi

jersey - jersey jax-rs Web服务中的init方法

转载 作者:行者123 更新时间:2023-12-04 22:43:06 25 4
gpt4 key购买 nike

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

我需要的是一种方法,服务启动后即被称为。在这种方法中,我想加载自定义配置文件,设置一些属性,编写日志等等。

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

我必须意识到哪些选择?

请告诉我,如果需要一些依赖关系,请给我一个如何将其添加到pom.xml中的想法(否则)

最佳答案

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

从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
}
}

在这种方法中,必须使用 @ApplicationScoped包中的 javax.enterprise.context @ApplicationScoped包中的 而不是 javax.faces.bean

从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

关于jersey - jersey jax-rs Web服务中的init方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39821157/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com