What is the difference between these two types of spring GET methods? Which one is the preferred method?
@Component
@Scope("request")
@Path("/")
public class TestComponent {
@GET
@Path("/hello")
public String printHello() {
return "hello";
}
}
vs
@Controller
public class TestController {
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String printHello() {
return "hello"
}
}
The first method is JAX-RS methos and is compatible with any JAX-RS implementation.
The second one use the Spring MVC annotations and is only compatible with Spring MVC.
Only one of the two examples you posted is an actual Spring GET, and that is the second one
@RequestMapping(value = "/hello", method = RequestMethod.GET)
annotation. It is a Spring MVC implementation.The other one, the first
@GET @Path("/hello")
, is actually a JAX-RS GET specification, and you will need an implementation of the JAX-RS to make it work.The main differences between them are not on the "GET" only, but on the overall frameworks. There are already detailed articles like this one covering the differences between JAX-RS and Spring MVC RESTful.
Since REST is not a formal specification, implementations of it may vary slightly from one provider from another, but the concept is the same.
Spring MVC's RESTful will be more tightly integrated into the Spring Framework.
JAX-RS will follow the Java EE implementation, and the integration will benefit a full Java EE environment.
And you can also "merge" Spring and Java EE as well. There are connectors that can integrate Spring and JAX-RS so you can benefit from one or another. See this example.
So the preferred method depends. Generally speaking:
I found Spring easier to configure and set up in Tomcat, but that is my opinion. Also the Spring exception handling
@ControllerAdvice
and@ExceptionHandler
solved my RESTful JSON handling perfectly for what I was needing, but maybe there is something similiar for JAX-RS too.As a final statement I think you should define your RESTful framework (JAX-RS, Spring, or even another one) based mainly on which environment you are going to run on, but also considering all the integrations and resources you are going to need for yor project.