猿问

使用Jersey2.0的依赖注入

使用Jersey2.0的依赖注入

从零开始,在没有任何先前Jersey1.x知识的情况下,我很难理解如何在Jersey2.0项目中设置依赖注入。

我也知道在泽西岛2.0版中可以使用HK2,但我似乎找不到有助于泽西岛2.0集成的文档。

@ManagedBean@Path("myresource")public class MyResource {

    @Inject
    MyService myService;

    /**
     * Method handling HTTP GET requests. The returned object will be sent
     * to the client as "text/plain" media type.
     *
     * @return String that will be returned as a text/plain response.
     */
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/getit")
    public String getIt() {
        return "Got it {" + myService + "}";
    }}@Resource@ManagedBeanpublic class MyService {
    void serviceCall() {
        System.out.print("Service calls");
    }}

柚木

<properties>
    <jersey.version>2.0-rc1</jersey.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.glassfish.jersey</groupId>
            <artifactId>jersey-bom</artifactId>
            <version>${jersey.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies></dependencyManagement><dependencies>
    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-common</artifactId>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-server</artifactId>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey</groupId>
        <artifactId>jax-rs-ri</artifactId>
    </dependency></dependencies>



我的入门项目可在GitHub获得:https://github.com/donaldjarmstrong/jaxrs


小唯快跑啊
浏览 957回答 3
3回答

白板的微信

所选答案可追溯到前一段时间。在一个定制的HK2活页夹中声明每一个装订都是不实际的。我正在使用Tomcat,我只需要添加一个依赖项。尽管它是为玻璃鱼设计的,但它完全适合其他容器。&nbsp;&nbsp;&nbsp;<dependency> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<groupId>org.glassfish.jersey.containers.glassfish</groupId> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<artifactId>jersey-gf-cdi</artifactId> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<version>${jersey.version}</version> &nbsp;&nbsp;&nbsp;&nbsp;</dependency>也要确保容器配置正确(见文件).
随时随地看视频慕课网APP

相关分类

Java
我要回答