How can I enable CDI with Jersey Test Framework?

自闭症网瘾萝莉.ら 提交于 2019-12-04 12:48:44

I found a solution.

I added following additional dependencies.

<dependency>
  <groupId>org.glassfish.jersey.ext.cdi</groupId>
  <artifactId>jersey-cdi1x</artifactId>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>org.glassfish.jersey.ext.cdi</groupId>
  <artifactId>jersey-weld2-se</artifactId>
  <scope>test</scope>
</dependency>

Now Weld takes over HK2, I think. I don't know what jersey-cdi1x-ban-custom-hk2-binding is for. Anyway, I can use standard annotations from javax.enterprise:cdi-api.

public class MyProducer {

    @Produces @Some
    public MyType produceSome() {}

    public void disposeSome(@Disposes @Some MyType instance) {}
}

And an initialisation code for Weld added.

@Override
protected Application configure() {

    // this method works somewhat weirdly.
    // local variables including logger
    // is null in here
    // I have to start (and join) a thread
    // which initializes Weld and adds a shutdown hook

    final Thread thread = new Thread(() -> {
        final Weld weld = new Weld();
        weld.initialize();
        Runtime.getRuntime().addShutdownHook(
            new Thread(() -> weld.shutdown()));
    });
    thread.start();
    try {
        thread.join();
    } catch (final InterruptedException ie) {
        throw new RuntimeException(ie);
    }

    final ResourceConfig resourceConfig
        = new ResourceConfig(MyResource.class);

    resourceConfig.register(MyProducer.class);

    return resourceConfig;
}

Every points get injected and all lifecycle methods are invoked. Yay!!!


I don't understand why I tried to use a thread in the first place.

@Override
protected Application configure() {

    final Weld weld = new Weld();
    weld.initialize();
    Runtime.getRuntime().addShutdownHook(new Thread(() -> weld.shutdown()));

    final ResourceConfig resourceConfig
        = new ResourceConfig(MyResource.class);

    resourceConfig.register(MyProducer.class);

    return resourceConfig;
}

Since I use JerseyTestNg.ContainerPerClassTest I failed, at least with TestNG, to work with @BeforeClass and @AfterClass because configure() method is invoked (indirectly) from the constructor.

I think I can use @BeforeMethod and @AfterMethod for initializing/shutting-down Weld if I switch to JerseyTestNg.ContainerPerMethodTest.


jersey-cdi1x is a transitive dependency of the jersey-weld2-se so it can be omitted.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!