Sunday, October 20, 2019

Configure Jersey with Annotations only

We need a class that extends the javax.ws.rs.core.Application which will register the jersey application with the help of the @ApplicationPath annotation.

Add jersey dependencies to your classpath.

 <dependencies>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-json-jackson</artifactId>
            <version>${jersey.version}</version>
        </dependency>
    </dependencies>


1. We need to extend the javax.ws.rs.core.Application class to configure jersey.
2. We can manually register the rest services by overriding the getClasses() method. But in this example we use a package scanner to automatically pickup rest services in our application. By overriding the getProperties() metod and registering the property
3. jersey.config.server.provider.packages with the packages to search for rest services in our project, jersey is able to automatically register the rest services. Finally we need to map a context path that jersey must listen to. We can achieve this by annotating our class with the @ApplicationPath annotation.

package com.memorynotfound.rs;

import java.util.HashMap;
import java.util.Map;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("/api")
public class ApplicationConfig extends Application {

    @Override
    public Map<String, Object> getProperties() {
        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put("jersey.config.server.provider.packages", "com.memorynotfound.rs");
        return properties;
    }
}

link : https://memorynotfound.com/configure-jersey-with-annotations-only/

JAX-RS provides the @Context annotation to inject a variety of resources in your RESTful services. Some of the most commonly injected components are HTTP headers, HTTP URI related information.






No comments:

Post a Comment