jersey jax-rs Web服务中的init方法 [英] init method in jersey jax-rs web service
问题描述
我是jax-rs的新手,并且已经用球衣和glassfish构建了Web服务.
I'm new with jax-rs and have build a web service with jersey and glassfish.
我需要的是一种方法,服务启动后即被调用.在这种方法中,我想加载自定义配置文件,设置一些属性,编写日志等等...
What I need is a method, which is called once the service is started. In this method I want to load a custom config file, set some properties, write a log, and so on ...
我尝试使用servlet的构造函数,但是每次调用GET或POST方法时都会调用该构造函数.
I tried to use the constructor of the servlet but the constructor is called every time a GET or POST method is called.
我必须意识到哪些选择?
what options I have to realize that?
请告诉我们,如果需要一些依赖项,请给我一个想法,如何将其添加到pom.xml中(否则)
Please tell, if some dependencies are needed, give me an idea how to add it to the pom.xml (or else)
推荐答案
有多种方法可以实现它,具体取决于应用程序中可用的内容:
There are multiple ways to achieve it, depending on what you have available in your application:
一旦JAX-RS建立在Servlet API的顶部,下面的代码就可以解决问题:
Once JAX-RS is built on the top of the Servlet API, the following piece of code will do the trick:
@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
}
}
使用 @ApplicationScoped
和<来自CDI的a href ="http://docs.oracle.com/javaee/7/api/javax/enterprise/event/Observes.html" rel ="noreferrer"> @Observes
将JAX-RS与CDI结合使用时,您可以拥有以下内容:
Using @ApplicationScoped
and @Observes
from CDI
When using JAX-RS with CDI, you can have the following:
@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
包中获得,而不是 包中的rel ="noreferrer"> @ApplicationScoped
.
In this approach, you must use @ApplicationScoped
from the javax.enterprise.context
package and not @ApplicationScoped
from the javax.faces.bean
package.
将JAX-RS与EJB一起使用时,您可以尝试:
When using JAX-RS with EJB, you can try:
@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
}
}
如果您有兴趣阅读属性文件,请检查此问题.如果您使用的是CDI,并且愿意向您的项目添加 Apache DeltaSpike 依赖项,请考虑查看此 answer .
If you are interested in reading a properties file, check this question. If you are using CDI and you are open to add Apache DeltaSpike dependencies to your project, considering having a look at this answer.
这篇关于jersey jax-rs Web服务中的init方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!