How do I initialize Jersey with a specific resource instance with specific MessgeBodyReaders / Writers?
I am trying to run Jersey on a preconfigured port / url with a preconfigured resource instance. I cannot figure out how to do this correctly.
Here is a code snippet. Help me fill in the blanks:
@Component
@PerRequest
@Path("/svc")
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public class MyService
{
// This piece is known
}
public class JSONMessageBodyWriter implements MessageBodyWriter<Object>
{
// This piece is known
}
public class XMLMessageBodyWriter implements MessageBodyWriter<Object>
{
// This piece is known
}
// This is where I need help
MyService service = new MyService();
...
HttpHandler handler = ???
...
HttpServer server = ???
server.createContext("/services", handler);
...
server.start();
In the above snippet, I am trying to open MyService via http: // localhost: 8080 / services / svc url. If JSONMessageBodyWriter and XMLMessageBodyWriter are connected, the service will work with XML and JSON, respectively.
If you know how to do this on Jetty or Grizzly, let me know. Can Spring help here?
a source to share
Jersey itself has a whole set of examples , and in particular, the simplest example helloworld shows how to start a server on a port, or just start it or test it in JUnits. If you look at this, you get an example of how to get the server up and running.
Now when you configure MessageBodyReaders and MessageBodyWriters as part of a jersey application, you will find that this is covered by the JAX-RS specification itself (which uses jersey). First, your reader and writer needs the @Provider annotation. Also, the reader should get the @Consumes annotation and the writer should get the @Produces annotation, so you can specify which types and mime types they consume and produce respectively.
Then they are activated. The helloworld example above won't show because it doesn't use custom readers or writers (another example might, I haven't looked). So instead of shipping a package to find resources (like they do, you will know what I'm talking about when you see the helloworld example), you will code an application subclass where you specify your resource class and reader / writer classes. With a reader and writer, you have the option to specify the class (which you return from getClasses) or provide an already created instance yourself (which you return from getSingletons).
Finally, specify the name of your Application subclass as the value for the init parameter "javax.ws.rs.Application"
. The init-params parameter can be passed to the GrizzlyWebContainerFactory.create (again, you will see this is used in the example) when starting the server.
Hope it helps.
a source to share