Sunday, January 30, 2011

Top X Saltation Mvc Together With Balance Annotations Alongside Examples For Coffee Programmers

Hello guys, welcome to my 3rd article on exploring essential annotations from the Spring framework, the most pop framework for Java development. In the offset article, I convey shared some of the most useful Spring Framework annotations, which were based upon Core Spring functionalities similar dependency injection, inversion of control, in addition to configuration, in addition to inward the instant article, nosotros convey learned nigh of import Spring Cloud annotations like @EnableConfigServer, @EnableEurekaSever, in addition to @EnableDiscoveryClient. Now that you lot know those essential Spring annotations it's fourth dimension to motion towards Spring MVC in addition to REST, 1 of the most used parts of Spring Framework.

In this article, you lot volition acquire some of the essential Spring MVC in addition to REST annotations similar @Controller, @RequestMapping, in addition to @RestController. These annotations are really useful for creating Spring-based Java spider web application in addition to RESTful spider web services.

I specially similar Spring MVC's back upwardly for developing RESTful spider web services inward Java. As I convey explained inward my before article 7 reasons to utilisation Spring MVC for REST inward Java, it provides convenient annotations similar @RestController, @ResponseBody, in addition to @ResponseStatus to create fully functional REST APIs inward Java.

In add-on to exploring total Spring MVC annotations similar @RequestMapping, @RequestParam, in addition to @PathVariable, we'll also explore those which are immensely helpful for developing REST APIs inward Java.

Btw, if you lot convey worked inward Spring MVC thus you lot should already convey some basic ideas nigh these annotations, but if you lot don't convey whatever prior sense in addition to only started amongst Spring framework in addition to Spring MVC thus I propose you lot to offset acquire through a comprehensive course of written report similar Spring Framework 5: Beginner to Guru course of written report on Udemy.  One of the most useful courses on Spring framework.





10 Spring MVC in addition to REST annotations for Java developers

Without wasting whatever to a greater extent than of your time, hither is my listing of some of the must-know Spring MVC in addition to REST annotations for Java developers. If you lot convey used Spring MVC to create a spider web application or RESTful applications thus you lot should already move familiar amongst these but if you lot haven't don't worry, you'll acquire inward this article.

 welcome to my 3rd article on exploring essential annotations from the Spring framework Top 10 Spring MVC in addition to REST Annotations amongst Examples for Java Programmers


Btw, I'll non acquire inward besides much particular nigh roofing every unmarried alternative in addition to functionality of these annotations, only to proceed this article inward reasonable length, but volition give you lot resources similar Spring inward Action majority where you lot tin acquire these annotations in addition to their utilisation inward depth.


1. @Controller

This annotation is used to brand a degree every bit spider web controller, which tin conduct maintain customer requests in addition to shipping a reply dorsum to the client. This is a degree flat annotation, which is position on top of your controller class. Similar to @Service in addition to @Repository it is also a stereotype annotation. If you lot are wondering what is the departure betwixt them thus you lot tin also run across this article to acquire to a greater extent than nigh their differences.

Here is an event of @Controller annotation inward Spring MVC:

@Controller public class HelloController{ // handler methods }

This is a uncomplicated controller degree which contains handler methods to conduct maintain HTTP asking for unlike URLs. You don't need to extend a degree or implement an interface to create the controller anymore.



2. @RequestMapping

The Controller degree contains several handler methods to conduct maintain unlike HTTP asking but how does Spring map a particular asking to a particular handler method? Well, that's done amongst the assist of the @RequestMapping annotation. It's a method flat annotation which is specified over a handler method.

It provides the mapping betwixt the asking path in addition to handler method. It also supports some advanced alternative which tin move used to specify split handler methods for unlike types of asking on the same URI similar you lot tin specify a method to conduct maintain GET request in addition to some other to conduct maintain POST asking on same URI.

Here is an event of @RequestMapping annotation inward Spring MVC:

@Controller public class HelloControler{    @RequestMapping("/")   public String hello(){     return "Hello Spring MVC";   } }

In this example, the dwelling page volition map to this handler method. So whatever asking comes to the localhost:8080 volition acquire to this method which volition render "Hello Spring MVC".

The value attribute of @RequestMapping annotation is used to specify the URL pattern but if at that topographic point are no to a greater extent than arguments thus you lot also omit that.

You tin also specify the HTTP method using RequestMethod attribute. If you lot are novel to Spring MVC, I propose you lot acquire through  @RequestParam annotation inward Spring MVC from my before article nigh the departure betwixt RequestParam in addition to PathVariable annotation:

@RequestMapping("/book") world String showBookDetails(  @RequestParam("ISBN") String ISBN, Model model){   model.addAttribute("ISBN", ISBN);   render "bookDetails"; }

If you lot access your spider web application which provides majority details amongst a query parameter similar below:

http://localhost:8080/book?ISBN=900848893

thus inward a higher house handler method volition move called because it is outpouring to the "/book" URL in addition to the query parameter ISBN volition move used to populate the method declaration amongst the same parent "ISBN" within showBookDetails() method.

You tin fifty-fifty utilisation a unlike parent of your choice. If you lot are interested inward learning to a greater extent than nigh @RequestParam annotation in addition to its diverse options thus Spring MVC For Beginners: Build Java Web App inward 25 Steps on Udemy is a bang-up house to start with.

 welcome to my 3rd article on exploring essential annotations from the Spring framework Top 10 Spring MVC in addition to REST Annotations amongst Examples for Java Programmers



4. @PathVariable

This is some other annotation which is used to remember information from the URL. Unlike @RequestParam annotation which is used to extract query parameters, this annotation enables the controller to conduct maintain a asking for parameterized URLs similar URLs that convey variable input every bit portion of their path like:

http://localhost:8080/books/900083838

If you lot desire to remember the ISBN let on "900083838" from the URL every bit method declaration thus you lot tin utilisation @PathVariable annotation inward Spring MVC every bit shown below:

@RequestMapping(value="/books/{ISBN}",                         method= RequestMethod.GET) world String showBookDetails(@PathVariable("ISBN") String id, Model model){    model.addAttribute("ISBN", id);    render "bookDetails"; }

The Path variable is represented within curly braces similar {ISBN}, which agency the portion later /books is extracted in addition to populated on method declaration id, which is annotated amongst @PathVaraible.

In short, this annotation binds placeholder from the URI to a method parameter within the handler method. This is immensely useful piece developing RESTful spider web services which contains useful information every bit portion of their URL.



5. @RequestBody

This annotation tin convert inbound HTTP information into Java objects passed into the controller's handler method. Just every bit @ResponseBody tells the Spring MVC to utilisation a message converter when sending a reply to the client, the @RequestBody annotations tell the Spring to notice a suitable message converter to convert a resources representation coming from a customer into an object.

Here is an example:

@RequestMapping(method=RequestMethod.POST, consumers= "application/json") world @ResponseBody Course saveCourse(@RequestBody Course aCourse){    render courseRepository.save(aCourse); }

This is 1 time to a greater extent than a really useful annotation piece developing RESTful spider web service inward Java using Spring framework in addition to 1 of the reasons why I dearest to write RESTful API using Spring.

If you lot are also interested inward developing RESTful application inward Java thus I propose going through Eugen Parachiv's REST amongst Spring Certification class on Baeldung. He has shared his years of sense inward developing REST-based applications using Spring inward this course.




6. @ResponseBody

The @ResponseBody annotation is 1 of the most useful annotations for developing RESTful spider web service using Spring MVC. This annotation is used to transform a Java object returned from he a controller to a resources representation requested past times a REST client. It tin completely bypass the persuasion resolution part.

Here is an event of @ResponseBody annotation inward Spring MVC:

@RequestMapping(method=RequestMethod.POST,consumers= "application/json") world @ResponseBody Course saveCourse(@RequestBody Course aCourse){   render courseRepository.save(aCourse); }

This is the same every bit the previous event but the @ResponseBody is used to betoken that the reply returned past times this method volition move converted into a resources which the customer tin consume.

If you lot convey created whatever RESTful spider web service amongst Spring MVC thus you lot know that nosotros need to annotate each method which generates REST reply amongst the @ResponseBody annotation but amongst the introduction of @RestController, nosotros tin avoid this.




7. @RestController

This is convenience annotation for developing RESTful spider web service amongst Spring MVC framework. The @RestController is a combination of @Controller in addition to @ResponseBody, which was introduced inward the Spring 3.4 version.

When you lot annotate a controller degree amongst @RestController it does 2 purposes, first, it says that the controller degree is treatment a asking for REST APIs in addition to instant you lot don't need to annotate each method amongst the @ResposneBody annotation to signal that the reply volition move converted into a Resource using diverse HttpMessageConverers.

Here is an event of @RestController annotation inward Spring MVC:

@RestController class HelloControler{  @RequestMapping("/") public String hello(){   return "Hello Spring Booot"; }  }

You tin run across that at that topographic point is no @ReseponseBody annotation is required to generate RESTful response. Before @RestController, Java developer used @Controller on top of the degree in addition to annotated each handler method amongst @ResponseBody annotation.

Spring designer saw this in addition to brand life easier past times introducing @RestController. If you lot are interested, you lot tin acquire to a greater extent than nigh it on RESTful Web Services amongst Java in addition to Spring, a comprehensive course of written report for developing a existent globe in addition to secure REST API amongst Java in addition to Spring.
You volition also acquire about Implementing API calls, Sign-up, sign-in, e-mail verification, password reset, update, delete in addition to fifty-fifty how to deploy RESTFul Java apps on Amazon AWS Cloud.

 welcome to my 3rd article on exploring essential annotations from the Spring framework Top 10 Spring MVC in addition to REST Annotations amongst Examples for Java Programmers



8. @SprinbBootApplication

This is a relatively novel annotation but really useful if you lot are using Spring Boot for creating Java spider web application amongst Spring. This unmarried annotation combines 3 annotations similar @Configuration, @EnableAutoConfiguration, in addition to @ComponentScan. If you lot utilisation Spring Boot, thus you lot tin run your application without deploying into a spider web server, every bit it comes amongst an embedded Tomcat server.

When you lot annotated your Main degree amongst @SpringBootApplication thus it enables Java-based configuration every bit good every bit ingredient scanning in addition to auto-configuration characteristic of Spring Boot, which tin magically laid things for you lot past times only dropping the required JAR into classpath.

hither is an event of using @SpringBootApplicaiton annotation inward Spring:

import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;  @SpringBootApplication  // same every bit @Configuration @EnableAutoConfiguration @ComponentScan public class SpringBootApp{   public static void main(String[] args) {   SpringApplication.run(SpringBootApp.class, args);  }  }

Since Spring Boot provides many features to brand Java evolution amongst Spring easier, I propose you lot to utilisation Spring Boot going forward. If you lot are novel to Spring kick then Spring Boot MasterClass course on Udemy is 1 of the valuable resources to acquire in addition to original Spring Boot.



9. @EnableAutoConfiguration

This is some other Spring kick annotation which enables the auto-configuration feature, which makes Spring jurist the configuration based on the JAR presents inward the classpath.

This is genuinely the original annotation which was used to enable/disable auto-configuration, nowadays from the really offset liberate of Spring Boot. Since it was constantly used amongst @Configuration in addition to @ComponentScan on an before version of Spring boot, they convey come upwardly up amongst a convenience @SpringBootApplication annotation.

Though you lot tin yet utilisation @EnableAutoConfiguration annotation if you lot desire to customize or convey some command over auto-configuration.

For example, you lot tin exclude surely classes from auto-configuration every bit shown inward the next event from my before post nigh the departure betwixt @SpringBootApplication in addition to @EnableAutoConfiguration inward Spring boot:

@Configuration @EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) public class MyConfiguration {   //.. Java code }

If you lot desire to acquire to a greater extent than nigh this annotation thus Spring Boot inward Action past times Craig Walls is 1 of the best resources to start with.



10. @ResponseStatus

This annotation tin move used to override the HTTP reply code for a response. You tin utilisation this annotation for mistake treatment piece developing a spider web application or RESTful spider web service using Spring. Here is an event of @ResponseStatus inspired past times my favorite Spring inward Action book:

@Exceptionhandler(BookNotFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) public Error bookNotFound(BookNotFoundException bnfe){   long ISBN = bnfe.getISBN();   return new Error(4, "Book [" + ISBN + "] non found"); }

Here nosotros are returning an mistake if the majority for given ISBN is non establish inward our library in addition to nosotros convey used @ResponseStatus to override the HTTP condition code every bit 404 to betoken customer a missing resource.


That's all nigh some of the essential Spring MVC in addition to REST annotations. As a Java developer, you lot should move familiar amongst these annotations, especially if you lot are using Spring MVC for creating a spider web application or RESTful spider web service inward Java. If you lot desire to acquire to a greater extent than nigh these annotations in addition to diverse options to configure in addition to utilisation them, hither are some resources you lot tin consult.

Further Learning
Master Microservices amongst Spring Boot in addition to Spring Cloud
Top 5Spring in addition to Hibernate Trainign courses
5 Free Spring Framework in addition to Spring Boot Courses
15 Spring Boot Interview Questions amongst Answers
Top 10 Spring Framework Interview Questions
20 REST amongst Spring Interview Questions for Web developers
3 ways to acquire Core Spring or Spring MVC better
6 Courses to acquire Spring Framework inward Depth
30+ Spring MVC Interview Questions for Java Developers
How to crevice Spring Core Professional 5.0 Certification

Thanks for reading this article thus far. If you lot notice these Spring MVC annotations useful thus delight portion amongst your friends in addition to colleagues on Facebook in addition to Twitter. If you lot convey whatever questions or feedback thus delight drib a note.

No comments:

Post a Comment