Spring boot is an open source, microservice-based Java framework. It is a favorite of developers due to its auto configuration feature, ease of building applications and the reduction of boiler plate code. Try out a simple spring boot application to see how quick you can create a production ready application with just few clicks. Wondering how it’s possible? Read through to find out the magic, that does the work for you behind the scenes.
Annotations are a form of metadata which provide data about a program. They help us to manage and configure the behavior of the framework. They are quick, easy to use, and faster than building the equivalent functionality ourselves. They provide a lot of value and that's why it's important for a Java developer to get familiar with essential annotations of the framework.
In this article let’s learn about some frequently used basic spring boot annotations
Application set up annotations : @SpringbootApplication @Configuration @ComponentScan @EnableAutoConfiguration Spring boot basic annotations : @Controller @Service @Repository @Entity @Autowired @Bean REST annotations : @RestController @RequestBody @ResponseBody @PathVariable @RequestParam |
Application set up annotations :
@SpringbootApplication
It is used to denote the main class of the application. It combines three annotations, @Configuration, @EnableAutoConfiguration, @ComponentScan. This class automatically creates the ApplicationContext from the classpath, scans the configuration classes and launches the application.
@Configuration
This @Configuration annotation is used as a source of bean definitions. It is a marker annotation which 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
It is an analog for the XML configuration file.
@ComponentScan
Typically, in Spring boot application, annotations like @Component, @Configuration, @Service, @Repository are specified on classes to mark them as Spring beans. The @ComponentScan annotation tells Spring Boot to scan the current package and its sub-packages in order to identify all the annotated classes and configure them as Spring beans. Thus, it designates the current package as the root package for component scanning.
@EnableAutoConfiguration
@EnableAutoConfiguration, as its name says, enables auto-configuration. It means that Spring Boot looks for auto-configuration beans on its classpath and automatically applies them. The package of the class declaring the @EnableAutoConfiguration annotation is considered as the default. Therefore, we need to apply the @EnableAutoConfiguration annotation in the root package so that every sub-packages and class can be examined.
@SpringBootApplication
public class LmsServicesApplication {
public static void main(String[] args) {
SpringApplication.run(LmsServicesApplication.class, args);
}
}
|
Spring boot basic annotations :
@Controller
This annotation is used to make a class as a web controller, which can handle client requests and send a response back to the client. It is most commonly used with @RequestMapping annotation, which provides the mapping between the request path and the handler method.
@Service
It is used to mark the class as a service provider. So overall @Service annotation is used with classes that provide service implementation including business logic, calculations, call external APIs, etc. Generally, it holds the business logic of the application.
@Repository
@Repository Annotation is a specialization of @Component annotation which is used to indicate that the class provides the mechanism for storage, retrieval, update, delete and search operation on objects. It is used on java classes which directly access the database. It acts as a marker for any class that is used as a repository or DAO (Data Access Object).
@Entity
@Entity indicates the class as a JPA entity, which makes the object ready for storage in a JPA-based data store. If we do not define @Table annotation, Spring config will assume that this entity is mapped to a table like the POJO class name.
@Autowired
The @Autowired annotation is used to automatically inject dependencies of the specified type into the current bean. It provides more fine-grained control over where and how autowiring should be accomplished.
@Bean
A Spring IoC container is the core of the spring framework. The container will create the objects, wire them together, configure them, and manage their complete life cycle from creation till destruction. These objects are known as Spring Beans.@Bean annotation signifies that the given method creates a bean which is managed by the Spring Container.
Contoller example
@RestController @RequestMapping("/assignments") public class AssignmentController { @Autowired private AssignmentService assignmentService; //get assignment by id @GetMapping("/{id}") public ResponseEntity<AssignmentDto> getAssignmentById(@PathVariable(value="id") Long id) { return ResponseEntity.ok(this.assignmentService.getAssignmentById(id)); } } |
Service example
@Service public class AssignmentService { @Autowired private AssignmentRepository assignmentRepository; @Autowired private AssignmentMapper assignmentMapper; //get assignment by id public AssignmentDto getAssignmentById(Long id) { Assignment assignment = this.assignmentRepository.findById(id) .orElseThrow(() -> new ResourceNotFoundException("Assignment", "Id", id)); return assignmentMapper.toAssignmentDto(assignment); } } |
Repository example
@Repository public interface AssignmentRepository extends JpaRepository<Assignment, Long> { public Optional<Assignment> findByAssignmentName(String assignmentName); public List<Assignment> findByBatch(Batch batch); } |
Entity example
@Entity @Getter @Setter @NoArgsConstructor @AllArgsConstructor @Table(name = "tbl_lms_assignments") public class Assignment { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name="a_id") private Long assignmentId; @NotEmpty @Column(name="a_name") private String assignmentName; @NotEmpty @Column(name="a_description") private String assignmentDescription; } |
REST Annotations :
@RestController
Rest Controller takes care of mapping request data to the defined request handler method. Once the response body is generated from the handler method, it converts it to JSON or XML response. The @RestController annotation is itself annotated with the @ResponseBody annotation. It eliminates the need for annotating each method with @ResponseBody.
@RequestBody
The @RequestBody annotations is used to bind HTTP request with an object in a method parameter. It can convert the inbound HTTP data into Java objects passed into the controller's handler method
@ResponseBody
This annotation is used to transform a Java object returned from the controller to a resource representation requested by a REST client. It indicates the Spring Boot Framework to serialize and return an object into JSON and XML format. It can completely bypass the view resolution part.
@PathVariable
The @PathVariable annotation is used to extract the values from the URI. Unlike @RequestParam annotation which is used to extract query parameters, this annotation enables the controller to handle a request with URLs that have variable input as part of their path. Multiple @PathVariable annotations can be defined in a method.
@RequestParam
The @RequestParam annotation is also called as the query parameter. It is used to extract the query parameters from the URL. It can define the default values if the query parameter is not present in the URL.
@RestController @RequestMapping("/assignments") public class AssignmentController { @Autowired private AssignmentService assignmentService; //create an assignment @PostMapping("") public ResponseEntity<AssignmentDto> createAssignment(@RequestBody AssignmentDto assignmentDto) { AssignmentDto createdAssignmentDto = this.assignmentService.createAssignment(assignmentDto); return new ResponseEntity<>(createdAssignmentDto, HttpStatus.CREATED); } //update an assignment @PutMapping("/{id}") public ResponseEntity<AssignmentDto> updateAssignment(@RequestBody AssignmentDto assignmentDto, @PathVariable Long id) { AssignmentDto updatedAssignmentDto = this.assignmentService.updateAssignment(assignmentDto, id); return ResponseEntity.ok(updatedAssignmentDto); } //delete an assignment @DeleteMapping("/{id}") public ResponseEntity<ApiResponse> deleteAssignment(@PathVariable Long id) { this.assignmentService.deleteAssignment(id); return new ResponseEntity<ApiResponse>(new ApiResponse("Assignment deleted successfully", true), HttpStatus.OK); } //get all assignments @GetMapping("") protected ResponseEntity<List<AssignmentDto>> getAllAssignments() { return ResponseEntity.ok(this.assignmentService.getAllAssignments()); } //get assignment by id @GetMapping("/{id}") public ResponseEntity<AssignmentDto> getAssignmentById(@PathVariable(value="id") Long id) { return ResponseEntity.ok(this.assignmentService.getAssignmentById(id)); } //get all batches of a program @GetMapping("/batch/{batchId}") public ResponseEntity<List<AssignmentDto>> getAssignmentsForBatch(@PathVariable(value="batchId") Integer batchId) { return ResponseEntity.ok(this.assignmentService.getAssignmentsForBatch(batchId)); } } |
I hope this gave a basic understanding of the important annotations to help you start off.
Don’t stop here though! There are many more annotations which can be used to simplify coding and help us get the most out of the framework.
Thanks for reading the article. Do share if you found it useful. Happy learning!!