简体   繁体   中英

How do I inject Jersey beans into Quartz job in Weld?

I have a pure JAX-RS application both in Glassfish and in jetty-servlet. I'm trying to inject some beans into Quartz job.

I've annotated Job fields with @javax.inject.Inject , but I also believe I need to make Job factory available to container, or vice versa - I'm somewhat lost here what end to start with.

How do I accomplish it?

Hi Victor without some more detail regarding your application I am going to assume you're running in a servlet container. There is no way to do it using a "pure" JAX-RS application.

However I would recommend you use CDI (Weld or OpenWebBeans). You can then use Deltaspike to enable the request context inside your Quartz job get a reference to a request scoped bean.

Enabling Weld in your servlet container is quite simple

A guide on enabling the request context outside of an HTTP request is available here

By default you cannot inject @RequestScoped beans into your quartz job (there is no HTTP request hence no request context). To work around this you can either enable the request context by following the link above OR (and probably my approach) inject @Dependent scoped beans (which do the work) into your JAX RS beans (essentially wrappers), you can then easily get references to the @Dependent scoped beans inside your quartz job.

Here is my web.xml and pom.xml for running Weld and Jersey inside jetty, you will need jetty-plus, jetty-jndi and Weld dependencies.

Here is some info about getting JNDI setup within jetty, however I do not use this method as I start jetty as an embedded container within a SE application, here is a code snippet of what I do:

String[] configurationClasses =
{
    "org.eclipse.jetty.webapp.WebInfConfiguration",
    "org.eclipse.jetty.webapp.WebXmlConfiguration",
    "org.eclipse.jetty.webapp.MetaInfConfiguration",
    "org.eclipse.jetty.webapp.FragmentConfiguration",
    "org.eclipse.jetty.plus.webapp.EnvConfiguration",
    "org.eclipse.jetty.webapp.JettyWebXmlConfiguration"
};
WebAppContext webapp = new WebAppContext();
webapp.setConfigurationClasses(configurationClasses);
webapp.setDescriptor("/path/to/webapp/WEB-INF/web.xml");
webapp.setContextPath("/");
webapp.setResourceBase("/path/to/webapp");
webapp.setClassLoader(Thread.currentThread().getContextClassLoader());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM