hstaudacher / osgi-jax-rs-connector

An OSGi - JAX-RS 2.0 Connector, software repository available on the link below
http://hstaudacher.github.io/osgi-jax-rs-connector
Other
190 stars 98 forks source link

Custom injector does not work! #115

Closed thanhlq closed 8 years ago

thanhlq commented 8 years ago

Hi, today I am trying to inject some custom object to a rest service but I am failed. Here is my code:

Suppose that I want to inject an object named UserContextInfo into my rest service as following:

public class ProductService implements IProductService {

@Context UserContextInfo uci; /* just like @Context HttpServletRequest req; */

}

During the authentication process (AuthenticationHandler), I set the uci variable into the ContainerRequestContext like this:

crc.setProperty("uci", uci);

The UserContextInfoFactory.java

public class UserContextInfoFactory implements Factory<UserContextInfo> {
    private final HttpServletRequest request;
    @Inject
    public UserContextInfoFactory(HttpServletRequest req) {
        this.request = req;
    }
    @Override
    public UserContextInfo provide() {
        return (UserContextInfo)request.getAttribute("uci");
    }
    @Override
    public void dispose(UserContextInfo t) {}
}

The UserContextInfoFactoryRegistration.java

public class UserContextInfoFactoryRegistration extends ResourceConfig {
    public UserContextInfoFactoryRegistration() {
        super.register(new AbstractBinder(){
            @Override
            protected void configure() {
                bindFactory(UserContextInfoFactory.class).to(UserContextInfo.class);
            }
        });
    }
}

During the debug, the uci is always null. Even that I can get the UserContextInfo object from HttpServletRequest.getAttribute("uci").

Thanks so much for your help to make this work...

Reference: https://jersey.java.net/documentation/latest/ioc.html#d0e15163

hstaudacher commented 8 years ago

I once wrote such User injector. It's open source. To start take a look at this: https://github.com/eclipsesource/connect/blob/master/bundles/com.eclipsesource.connect.inject/src/com/eclipsesource/connect/inject/ConnectInjectionFeature.java

This feature is registered as OSGi service. Hope this helps. Will close this issue because it's not an issue for the connector ;). Please feel free to reopen if you have any further questions.

thanhlq commented 8 years ago

Ok thanks very much for your sharing! I will look at your code.