Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use CDI into JAX-RS client

I have searched a while on SO and official documentation but I cannot found a way to use directly CDI injection into a JAX-RS client.

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

I want to use CDI injection and avoid registering each bean with HK2.

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

And MyWriter with the injected 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 running in an embedded jetty with Jersey 2 and Weld SE.

like image 379
Nicolas Henneaux Avatar asked Nov 08 '22 05:11

Nicolas Henneaux


1 Answers

Its possible to inject 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();

  }
}

Have a look at below doc

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

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

like image 125
gladiator Avatar answered Dec 06 '22 17:12

gladiator