将对象注入泽西资源

时间:2014-03-22 15:51:36

标签: java rest dependencies jersey code-injection

无法弄清楚如何在泽西服务器上创建一个可以在泽西资源中访问的对象。基本上,我想要做的是将数据库上下文注入到球衣资源中。

JerseyServer:

public boolean startServer(String keyStoreServer, String trustStoreServer) {
    //Check if GraphDb is setup
    if (gdbLogic == null) {
        //FIXME - maybe throw an exception here?
        return false;
    }

    // create a resource config that scans for JAX-RS resources and providers
    // in org.developer_recommender.server package
    final org.glassfish.jersey.server.ResourceConfig rc = new org.glassfish.jersey.server.ResourceConfig().packages("org.developer_recommender.server").register(createMoxyJsonResolver());

    WebappContext context = new WebappContext("context");
    ServletRegistration registration = context.addServlet("ServletContainer", ServletContainer.class);
    //TODO: value setzen
    registration.setInitParameter("jersey.config.server.provider.packages", "org.developer_recommender.server.service;org.developer_recommender.server.auth");
    registration.setInitParameter(ResourceConfig.PROPERTY_CONTAINER_REQUEST_FILTERS, SecurityFilter.class.getName());   
    SSLContextConfigurator sslContext = new SSLContextConfigurator();

    sslContext.setKeyStoreFile(keyStoreServer);
    sslContext.setTrustStoreFile(trustStoreServer);

    //TODO - 
    sslContext.setKeyStorePass("123456");
    sslContext.setTrustStorePass("123456");
    // create and start a new instance of grizzly http server
    // exposing the Jersey application at BASE_URI
    HttpServer server = null;
    try{
        SSLEngineConfigurator sslec = new SSLEngineConfigurator(sslContext).setClientMode(false).setNeedClientAuth(true);
        server = GrizzlyHttpServerFactory.createHttpServer(getBaseURI()/*URI.create(BASE_URI)*/, rc, true , sslec);
        System.out.println("Jersey app started. Try out " + BASE_URI);
        context.deploy(server);
        return true;
    } catch(Exception e ){
        System.out.println(e.getMessage());
    }

    return false;

服务:

public class Service {

    @Inject
    protected GDBLogic gbdLogic;

}

所以我希望在Jersey Resources中可以访问startServer中的GDBLogic实例。有关如何实现这一目标的任何建议? 我不想为GDBLogic使用静态字段来实现这一点,因为我们将至少有两种不同的数据库配置。

1 个答案:

答案 0 :(得分:1)

您需要设置实例绑定才能使注入工作。您可以通过在资源配置中添加HK2抽象活页夹来实现:

final ResourceConfig rc = new ResourceConfig()
    .packages("org.developer_recommender.server")
    .register(createMoxyJsonResolver())
    .register(new AbstractBinder() 
    {
        @Override
        protected void configure()
        {
            bind(gdbLogic).to(GDBLogic.class);
        }
    });