Spring Boot Important Annotations - Walking Techie

Blog about Java programming, Design Pattern, and Data Structure.

Friday, June 22, 2018

Spring Boot Important Annotations

In this post we will discuss about the basic spring boot annotations that are very important to know to start with spring boot. We will see these annotations mostly in every RESTful web service with spring boot.

Most important spring boot annotations:

SpringBootApplication

Indicates a configuration class that declares one or more @Bean methods and also triggers auto-configuration and component scanning. This is a convenience annotation that is equivalent to declaring @Configuration, @EnableAutoConfiguration and @ComponentScan.

Configuration

@Configuration annotation indicates that a class declares one or more @Bean methods and may be processed by the Spring container to generate bean definitions and service requests for those beans at runtime.

@Configuration
 public class AppConfig {

     @Bean
     public MyBean myBean() {
         // instantiate, configure and return bean ...
     }
 }

EnableAutoConfiguration

@EnableAutoConfiguration annotation enable auto-configuration of the Spring Application Context, attempting to guess and configure beans that you are likely to need.

The package of the class that is annotated with @EnableAutoConfiguration, usually via @SpringBootApplication, has specific significance and is often used as a 'default'. It is generally recommended that you place @EnableAutoConfiguration (if you're not using @SpringBootApplication) in a root package so that all sub-packages and classes can be searched.

RestController

@RestController annotation, which marks the class as a controller where every method returns a domain object instead of a view. It’s shorthand for @Controller and @ResponseBody rolled together.

RequestMapping

@RequestMapping annotation for mapping web requests onto methods in request-handling classes with flexible method signatures. @RequestMapping maps all HTTP operations by default.

Use @RequestMapping(method=GET) to narrow this mapping.

@RestController
@RequestMapping("/greeting")
public class GreetingController {
  @RequestMapping("/admin")
  public void greetingAdmin() {}
}

RequestParam

@RequestParam annotation which indicates that a method parameter should be bound to a web request parameter.

@RequestMapping(value = "/greeting", method = RequestMethod.GET)
public String greeting(@RequestParam("name") String name){
  return "Hello "+name;
}

PathVariable

@PathVariable annotation which indicates that a method parameter should be bound to a URI template variable.

@RequestMapping("/search/{id}")
public Long searchById(@PathVariable("id") Long id) {
  return id;
}

Using GetMapping with @PathVariable:

@GetMapping("/search/{id}")
public Long searchById(@PathVariable("id") Long id) {
  return id;
}

RequestBody

@RequestBody annotation indicating a method parameter should be bound to the body of the web request.

Optionally, automatic validation can be applied by annotating the argument with @Valid annotation.

@PostMapping("/create")
public void test(@Valid @RequestBody Payload payload) {
  //... do something
}

Controller

@Controller indicates that an annotated class is a "Controller" (e.g. a web controller). This annotation serves as a specialization of @Component, allowing for implementation classes to be autodetected through classpath scanning. It is typically used in combination with annotated handler methods based on the @RequestMapping annotation.

@Controller
@RequestMapping("/greeting")
public class GreetingController {

  @GetMapping("/search/{id}")
  @ResponseBody
  public Long searchById(@PathVariable("id") Long id) {
    return id;
  }
}

ResponseBody

@ResponseBody annotation that indicates a method return value should be bound to the web response body. Supported for annotated handler methods in Servlet environments.

As of version 4.0 this annotation can also be added on the type level in which case it is inherited and does not need to be added on the method level.

@Controller
@RequestMapping("/greeting")
public class GreetingController {

  @GetMapping("/search/{id}")
  @ResponseBody
  public Long searchById(@PathVariable("id") Long id) {
    return id;
  }
}

You can use the this annotation at type level so that you don't need to add at every method level.

@Controller
@RequestMapping("/greeting")
@ResponseBody
public class GreetingController {

  @GetMapping("/search/{id}")
  public Long searchById(@PathVariable("id") Long id) {
    return id;
  }
}

ComponentScan

Spring does not know about beans/components unless it know where to search it. Once you define a Component Scan for a package, Spring would search the package and all its sub packages for components/beans.

If your other packages hierarchies are below your main app with the @SpringBootApplication annotation, All components/beans will implicitly covered by components scan.

If youe beans/components packages are not sub packages of main package, You should manually add the @ComponentScan annotation.

Component

@Component indicates that an annotated class is a "component". Such classes are considered as candidates for auto-detection when using annotation-based configuration and classpath scanning; registered in application context as spring bean.

@Component
public class ComponentDemo {
}

Service

@Service indicates that an annotated class is a "service". This annotation is specialization of the @Component annotation. It doesn’t currently provide any additional behavior over the @Component annotation, but it’s a good idea to use @Service over @Component in service-layer classes because it specifies intent better.

Repository

@Repository annotation that indicates that the decorated class is a repository. A repository is a mechanism for encapsulating storage, retrieval, and search behavior which emulates a collection of objects. It is a specialization of the @Component annotation allowing for implementation classes to be autodetected through classpath scanning.

Bean

@Bean indicates that a method produces a bean to be managed by the Spring container.

@Bean
public MyBean myBean() {
   // instantiate and configure MyBean obj
   return obj;
}

Qualifier

This annotation may be used on a field or parameter as a qualifier for candidate beans when autowiring. It may also be used to annotate other custom annotations that can then in turn be used as qualifiers.

Autowired

Marks a constructor, field, setter method or config method as to be autowired by Spring's dependency injection facilities

@Component
public class GreetingComponent {
  // field autowired
  @Autowired private Environment env;

  // constructor autowired
  GreetingComponent(ApplicationContext context) {
    
  }
}

GetMapping

GetMapping annotation for mapping HTTP GET requests onto specific handler methods. Specifically, @GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET).

@GetMapping("/search/{id}")
public Long searchById(@PathVariable("id") Long id) {
  // do something ..
  return id;
}

PostMapping

PostMapping annotation for mapping HTTP POST requests onto specific handler methods. Specifically, @PostMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.POST).

@PostMapping("/create")
public void test(@Valid @RequestBody Payload payload) {
  //... do something
}

PutMapping

PutMapping annotation for mapping HTTP PUT requests onto specific handler methods. Specifically, @PutMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.PUT).

PatchMapping

PatchMapping annotation for mapping HTTP PATCH requests onto specific handler methods. Specifically, @PatchMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.PATCH).

DeleteMapping

DeleteMapping annotation for mapping HTTP DELETE requests onto specific handler methods. Specifically, @DeleteMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.DELETE).

1 comment :

  1. factorial hundred In the last few days, the “factorial of 100” is one of the top subjects and a lot of maths geeks compute it using voice assistants such as Alexa, Shiri, etc.
    factorial hundred In the last few days, the “factorial of 100” is one of the top subjects and a lot of maths geeks compute it using voice assistants such as Alexa, Shiri, etc.
    factorial hundred In the last few days, the “factorial of 100” is one of the top subjects and a lot of maths geeks compute it using voice assistants such as Alexa, Shiri, etc.


    ReplyDelete