0

我只是想在此处关注有关依赖注入的球衣文档:https ://jersey.java.net/documentation/latest/ioc.html#d0e15100

如果我尝试在参数上使用@Inject,我只会得到 grizzly 的请求失败页面。

有人可以告诉我我做错了什么吗?

主.java

public class Main extends ResourceConfig {
    // Base URI the Grizzly HTTP server will listen on
    public static final String BASE_URI = "http://0.0.0.0";
    public static URI getBaseURI(String hostname, int port) {
        return UriBuilder.fromUri("http://0.0.0.0/").port(port).build();
    }

    public Main() {
        super();

        String port = System.getenv("PORT");
        if(port == null) {
            port = "8080";
        }
        URI uri = getBaseURI(System.getenv("HOSTNAME"), Integer.parseInt(port));
        final HttpServer server = startServer(uri);
        System.out.println(String.format("Jersey app started with WADL available at "
                + "%sapplication.wadl\nHit enter to stop it...", BASE_URI));

        register(new AbstractBinder() {
            @Override
            protected void configure() {
                bindFactory(DaoFactory.class).to(TodoDao.class);
            }
        });

        try {
            while(true) {
                System.in.read();
            }
        } catch (Exception e) {

        }
    }

    /**
     * Starts Grizzly HTTP server exposing JAX-RS resources defined in this application.
     * @return Grizzly HTTP server.
     */
    public static HttpServer startServer(URI uri) {

        final ResourceConfig rc = new ResourceConfig().packages("com.example");

        return GrizzlyHttpServerFactory.createHttpServer(uri, rc);
    }

    /**
     * Main method.
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {

        Main m = new Main();

    }
}

TodoResource.java

@Path( "todos" )
public class TodoResource {

    @Inject Dao<String> dao;

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String getIt() {
        if(dao == null) {
            return "dao is null";
        }
        StringBuilder builder = new StringBuilder();
        for(int i = 0; i < dao.getAll().size(); i++) {
            builder.append(dao.getAll().get(i));
        }
        return builder.toString();
    }

}

道工厂.java

public class DaoFactory implements Factory<Dao>{

    private final Dao dao;


    @Inject
    public DaoFactory(Dao dao) {
        this.dao = dao;
    }

    @Override
    public Dao provide() {
        return dao;
    }

    @Override
    public void dispose(Dao d) {

    }
}
4

1 回答 1

3

您对绑定所做的操作是正确的。

但是,您绑定到@Contract 注解的接口“TodoDao”,这意味着它将寻找接口“TodoDao”进行注入。在您的类 TodoResource 中,您有“Dao<String>”,它不匹配。所以,如果你把它换成 TodoDao,它应该会找到并替换它。

现在,如果您想使用 Generic 而不是具体类,则必须使用带有包装器的实例化对象。某种形式的东西

bind(x.class).to(new TypeLiteral<InjectionResolver<SessionInject>>(){});

此外,如果您需要一些自动绑定的帮助(有点像 Spring),您可以使用以下文章:http ://www.justinleegrant.com/?p=516

于 2015-06-24T01:54:28.820 回答