Jetty Embedded, Jersey 2, Weld
Asked Answered
P

1

6

I'm using Jetty 9.1 and Jersey 2.5.1. Jersey has built-in support for Jetty, so I start my server like that:

public static void main(String[] args) {

    URI baseUri = UriBuilder.fromUri("http://localhost/").port(8080).build();
    ResourceConfig config = ResourceConfig.forApplicationClass(MyApplication.class);

    Server server = JettyHttpContainerFactory.createServer(baseUri, config);
}

MyApplication simply calls this.packages(...) to lookup my REST api classes.

However, the REST api class contains a @Inject annotated field, which should be injected by WELD. Obviously WELD is not started (CDI support not enabled), and weirder, it looks like HK2 (used by Jersey 2) is trying to perform the injection.

(I have a org.glassfish.hk2.api.UnsatisfiedDependencyException when hitting the REST endpoint).

How do I setup correctly WELD (preferably programmatically)?

Pyrone answered 8/1, 2014 at 15:8 Comment(1)
Make sure you are using Weld 2.2+ as it just fixed a few CDI integration bugs with Jetty 9.1+.Glue
P
3

I used Weld SE:

import org.jboss.weld.environment.se.Weld;
import org.jboss.weld.environment.se.WeldContainer;

And then simply

Weld weld = new Weld();
try {
    WeldContainer container = weld.initialize();

    URI baseUri = UriBuilder.fromUri("http://localhost/").port(8080).build();
    ResourceConfig config = ResourceConfig.forApplicationClass(MyApplication.class);

    Server server = JettyHttpContainerFactory.createServer(baseUri, config);

    server.join();

} catch (Exception e) {
    e.printStackTrace();
} finally {
    weld.shutdown();
}

Note that HK2 will handle REST classes, so I had to write a binder to make the injection work in those classes. This question helped me a lot.

Pyrone answered 9/1, 2014 at 15:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.