How to use CDI in a JAX-RS client

I searched for some time in SO and official documentation, but I did not find a way to directly use CDI injection in the JAX-RS client.

I retrieve the client using the builder method, and I want to register WriterInterceptor(or any filter-like component) that uses injection to retrieve another bean.

I want to use CDI injection and not register every bean with HK2.

ClientBuilder.newBuilder()
            .register(MyWriter.class)
            .build();

And MyWriter with the introduced class.

@Provider
public class MyWriter implements WriterInterceptor {
    private final MyRepo repo;

    @Inject
    public MyWriter(MyRepo repo) {
        this.repo = repo;
    }

    @Override
    public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {
        context.proceed();
    }
}

public class MyRepo {

}

I am launching an integrated jetty with Jersey 2 and Weld SE.

+4
source share
2 answers

It can be entered in java se application using wield.

 @Singleton
public class Application {

private static Logger logger = LoggerFactory.getLogger(Application.class);

    @inject
    private SomeOtherBean injectedBean;

public void run() {
    logger.debug("application initialized");
        injectedBean.doSomething();

}

}

inside main initialize weild

import java.io.IOException;

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

public class EntryPoint {

  public static void main(String[] args) throws IOException {

   Weld weld = new Weld();
   WeldContainer container = weld.initialize();
   Application application = container.instance().select(Application.class).get();
   application.run();
   weld.shutdown();

  }
}

doc

https://docs.jboss.org/weld/reference/latest/en-US/html/environments.html#_java_se

https://randling.wordpress.com/2011/08/15/cdi-in-java-se/

0

, . : H2K Binder, Weld Bean Manager. Bean H2K .

: , :

0

Source: https://habr.com/ru/post/1663056/


All Articles