草庐IT

java - 如何让 Google Guice 与 JaxRS( Jersey )一起工作

coder 2024-03-13 原文

我有一个可以轻松公开的基本 JAXRS 服务,但有一次我希望使用依赖项注入(inject) API,我怀疑 Google Guice 将是最好的服务之一。考虑到这一点,我尝试集成它,但文档有点繁重,我不得不四处寻找以尝试找到正确的组合

  • Web.xml
  • 上下文监听器(我应该使用 ServletContainer 还是 GuiceContainer)
  • 服务
  • 是否使用@Singleton 或@Request 来注释服务,或者什么都不用(我应该使用@Singleton 进行注释——文档说我应该,但随后又说它默认为请求范围)
  • 是否使用@InjectParam注解构造函数参数

但目前我从 Google Guice 收到错误,它们会根据我是否使用 @InjectParam 注释而改变。

如果我用@InjectParam 注释然后我得到

       Mar 29, 2013 9:52:04 PM com.sun.jersey.spi.inject.Errors processErrorMessages
   SEVERE: The following errors and warnings have been detected with resource and/or provider classes:
   SEVERE: The class com.hillingar.server.dao.interfaces.UserDao is an interface and cannot be instantiated.
   SEVERE: Missing dependency for constructor public com.hillingar.server.SessionUtility(com.hillingar.server.dao.interfaces.UserDao) at parameter index 0

如果我不注释然后我得到

    Mar 29, 2013 9:54:59 PM com.sun.jersey.spi.inject.Errors processErrorMessages
SEVERE: The following errors and warnings have been detected with resource and/or provider classes:
  SEVERE: Missing dependency for constructor public com.hillingar.server.rest.UserService(com.hillingar.server.dao.interfaces.UserDao,com.hillingar.server.SessionUtility) at parameter index 0
  SEVERE: Missing dependency for constructor public com.hillingar.server.rest.UserService(com.hillingar.server.dao.interfaces.UserDao,com.hillingar.server.SessionUtility) at parameter index 1

这是我的 web.xml

    <?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <filter>
        <filter-name>guiceFilter</filter-name>
        <filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>guiceFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <listener>
        <listener-class>com.hillingar.server.ServletContextListener</listener-class>
    </listener>

    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>

这是我的 ServletContextListener

package com.hillingar.server;

import java.util.logging.Logger;

import javax.servlet.ServletContextEvent;

import com.google.inject.Guice;
import com.google.inject.Singleton;
import com.hillingar.server.dao.jdbcImpl.UserJdbc;
import com.hillingar.server.dao.interfaces.UserDao;
import com.sun.jersey.guice.JerseyServletModule;
import com.sun.jersey.guice.spi.container.servlet.GuiceContainer;
import com.sun.jersey.spi.container.servlet.ServletContainer;

public class ServletContextListener implements javax.servlet.ServletContextListener {

    Logger logger = Logger.getLogger(this.getClass().getName());

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
    }

        /*
         * Covered in URL
         * https://code.google.com/p/google-guice/wiki/ServletModule
         */
    @Override
    public void contextInitialized(ServletContextEvent arg0) {

            // Note the user of JerseyServletModule instead of ServletModule
            // otherwise the expected constructor injection doesn't happen
            // (just the default constructor is called)
            Guice.createInjector(new JerseyServletModule() {
                @Override
                protected void configureServlets() {

                    /*
                     * Note: Every servlet (or filter) is required to be a 
                     * @Singleton. If you cannot annotate the class directly, 
                     * you must bind it using bind(..).in(Singleton.class), 
                     * separate to the filter() or servlet() rules. 
                     * Mapping under any other scope is an error. This is to 
                     * maintain consistency with the Servlet specification. 
                     * Guice Servlet does not support the 
                     * deprecated SingleThreadModel.
                     */
                    bind(SecurityFilter.class).in(Singleton.class);
                    bind(ServletContainer.class).in(Singleton.class);

                    /*
                     * Filter Mapping
                     * 
                     * This will route every incoming request through MyFilter, 
                     * and then continue to any other matching filters before 
                     * finally being dispatched to a servlet for processing.
                     * 
                     */

                    // SECURITY - currently disabled
                    // filter("/*").through(SecurityFilter.class);

                    /*
                     * Registering Servlets
                     * 
                     * This registers a servlet (subclass of HttpServlet) called 
                     * ServletContainer, the same one that I would have used in 
                     * the web.xml file, to serve any web requests with the 
                     * path /rest/*  i.e. ...
                     * 
                        <servlet>
                            <servlet-name>ServletAdaptor</servlet-name>
                            <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
                            <load-on-startup>1</load-on-startup>
                        </servlet>
                        <servlet-mapping>
                            <servlet-name>ServletAdaptor</servlet-name>
                            <url-pattern>/rest/*</url-pattern>
                        </servlet-mapping>

                     */
                    serve("/rest/*").with(ServletContainer.class); // JAX-RS

                    // Using this and it starts bitching about
                    // com.sun.jersey.api.container.ContainerException: The ResourceConfig instance does not contain any root resource classes.
                    // So presumably wants an Application class that enumerates 
                    // all my services?
                    //serve("/rest/*").with(GuiceContainer.class);

                    /*
                     * Bindings
                     */
                    bind(UserDao.class).to(UserJdbc.class);
                    bind(SessionUtility.class);
                }
            });
    }

}

这是我的用户服务

package com.hillingar.server.rest;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.SecurityContext;

import com.hillingar.server.SessionUtility;
import com.hillingar.server.dao.interfaces.UserDao;
import com.hillingar.server.model.User;
import com.hillingar.server.model.dto.AuthenticationResponse;

@Path("/user")
@Produces("application/json")
@Consumes({"application/xml","application/json"})
@Singleton // <-- Added Singleton here
public class UserService {

    private UserDao userDao;
    private SessionUtility sessionManager;

        /*
           Error if I annotate with @InjectParam...

           Mar 29, 2013 9:52:04 PM com.sun.jersey.spi.inject.Errors processErrorMessages
           SEVERE: The following errors and warnings have been detected with resource and/or provider classes:
           SEVERE: The class com.hillingar.server.dao.interfaces.UserDao is an interface and cannot be instantiated.
           SEVERE: Missing dependency for constructor public com.hillingar.server.SessionUtility(com.hillingar.server.dao.interfaces.UserDao) at parameter index 0

           Error If I don't annotate at all...
            Mar 29, 2013 9:54:59 PM com.sun.jersey.spi.inject.Errors processErrorMessages
            SEVERE: The following errors and warnings have been detected with resource and/or provider classes:
              SEVERE: Missing dependency for constructor public com.hillingar.server.rest.UserService(com.hillingar.server.dao.interfaces.UserDao,com.hillingar.server.SessionUtility) at parameter index 0
              SEVERE: Missing dependency for constructor public com.hillingar.server.rest.UserService(com.hillingar.server.dao.interfaces.UserDao,com.hillingar.server.SessionUtility) at parameter index 1

           (both output Initiating Jersey application, version 'Jersey: 1.13 06/29/2012 05:14 PM')
        */
    @Inject
    public UserService(UserDao userDao, SessionUtility sessionManager) {
        this.userDao = userDao;
                this.sessionManager = sessionManager;
    }

    @GET
    public List<User> test(@Context HttpServletRequest hsr) {
                // USER DAO IS ALWAYS NULL - CONSTRUCTOR INJECTION NOT WORKING
        User loggedInUser = userDao.findBySessionId(hsr.getSession().getId());
                ...
        return users;
    }

}

最佳答案

将 ServletContextListener 更改为

package com.hillingar.server;

import java.util.logging.Logger;

import javax.servlet.ServletContextEvent;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Singleton;
import com.google.inject.servlet.GuiceServletContextListener;
import com.hillingar.server.dao.jdbcImpl.UserJdbc;
import com.hillingar.server.dao.interfaces.UserDao;
import com.hillingar.server.rest.UserService;
import com.sun.jersey.guice.JerseyServletModule;
import com.sun.jersey.guice.spi.container.servlet.GuiceContainer;
import com.sun.jersey.spi.container.servlet.ServletContainer;

// (1) Extend GuiceServletContextListener
public class ServletContextListener extends GuiceServletContextListener {

    Logger logger = Logger.getLogger(this.getClass().getName());

    // (1) Override getInjector
    @Override
    protected Injector getInjector() {
        return Guice.createInjector(new JerseyServletModule() {
            @Override
            protected void configureServlets() {
                bind(SecurityFilter.class).in(Singleton.class);
                bind(UserService.class);// .in(Singleton.class);
                bind(ServletContainer.class).in(Singleton.class);

                // (2) Change to using the GuiceContainer
                serve("/rest/*").with(GuiceContainer.class); // <<<<---

                bind(UserDao.class).to(UserJdbc.class);
                bind(SessionUtility.class);
            }
        });
    }
}

关于java - 如何让 Google Guice 与 JaxRS( Jersey )一起工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15712233/

有关java - 如何让 Google Guice 与 JaxRS( Jersey )一起工作的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  4. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  5. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  6. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  7. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  8. ruby - 如何指定 Rack 处理程序 - 2

    Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack

  9. ruby - 如何每月在 Heroku 运行一次 Scheduler 插件? - 2

    在选择我想要运行操作的频率时,唯一的选项是“每天”、“每小时”和“每10分钟”。谢谢!我想为我的Rails3.1应用程序运行调度程序。 最佳答案 这不是一个优雅的解决方案,但您可以安排它每天运行,并在实际开始工作之前检查日期是否为当月的第一天。 关于ruby-如何每月在Heroku运行一次Scheduler插件?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/8692687/

  10. ruby-on-rails - 如何从 format.xml 中删除 <hash></hash> - 2

    我有一个对象has_many应呈现为xml的子对象。这不是问题。我的问题是我创建了一个Hash包含此数据,就像解析器需要它一样。但是rails自动将整个文件包含在.........我需要摆脱type="array"和我该如何处理?我没有在文档中找到任何内容。 最佳答案 我遇到了同样的问题;这是我的XML:我在用这个:entries.to_xml将散列数据转换为XML,但这会将条目的数据包装到中所以我修改了:entries.to_xml(root:"Contacts")但这仍然将转换后的XML包装在“联系人”中,将我的XML代码修改为

随机推荐