I thought, for a class to be inject-able, any class has to be annotated. But I am seeing one example demonstrating a simple REST service, where a class without any annotation is injected. HelloService isn't annotated. Is it a Bean? What about its scope of life cycle?
/**
* A simple CDI service which is able to say hello to someone
*
* @author Pete Muir
*
*/
public class HelloService {
String createHelloMessage(String name) {
return "Hello " + name + "!";
}
}
/**
* A simple REST service which is able to say hello to someone using HelloService Please take a look at the web.xml where JAX-RS
* is enabled And notice the @PathParam which expects the URL to contain /json/David or /xml/Mary
*
* @author bsutter@redhat.com
*/
@Path("/")
public class HelloWorld {
@Inject
HelloService helloService;
@POST
@Path("/json/{name}")
@Produces("application/json")
public String getHelloWorldJSON(@PathParam("name") String name) {
System.out.println("name: " + name);
return "{\"result\":\"" + helloService.createHelloMessage(name) + "\"}";
}
@POST
@Path("/xml/{name}")
@Produces("application/xml")
public String getHelloWorldXML(@PathParam("name") String name) {
System.out.println("name: " + name);
return "<xml><result>" + helloService.createHelloMessage(name) + "</result></xml>";
}
}
One more question in this example is that, why is it using "hello" in web.xml? There is no any class defined called "hello", and there is no any directory named as "hello" in the project.
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<!-- One of the ways of activating REST Servises is adding these lines.
The server is responsible for adding the corresponding servlet automatically.
The class org.jboss.as.quickstarts.html5rest.HelloWorld class has the
annotation @Path("/") to receive the REST invocation -->
<servlet-mapping>
<servlet-name>javax.ws.rs.core.Application</servlet-name>
<url-pattern>/hello/*</url-pattern>
</servlet-mapping>
</web-app>