JAX-RS register instance as an endpoint?

404 views Asked by At

I have a rest endpoint class similar to this:

@Path("/users")
public class Users {
    private final Database database;

    public Users(Database database) {
        this.database = database;
    }

    @GET
    @Path("/{id}")
    public Response Get(@PathParam("id") int id) {
        User user = this.database.get(id);
        return Response.ok(user).build();
    }
}

And a main method:

public class Main {
    public static void main(String[] args) {
        Database database = new SomeDBImplementation();
        Users users = new Users(database);
        
        HttpServer server = HttpServerFactory.create("http://localhost:8080");
        server.start();
    }
}

How do I make the server use the users instance as an endpoint? I'm using jersey-server

1

There are 1 answers

4
Paul Samsotha On BEST ANSWER

You need to create a ResourceConfig instance and then pass it to the HttpServerFactory.create(uri, resourceConfig) method. There are different implementations of ResourceConfig. The most basic one is the DefaultResourceConfig. To register a resource instance you would just do

ResourceConfig config = new DefaultResourceConfig();
config.getRootResourceSingletons().add(users);
HttpServer server = HttpServerFactory.create(uri, config);