INTRODUCTION

We are learning what is spring boot annotations. why we are using annotations in spring boot applications and their uses in project. How spring boot annotations made developers work easy using autoconfiguration in application.




Why annotations ? 

Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It also used to avoid the heavy XML configuration present in Spring. It does not change the action of the compiled program. So in this article, we are going to discuss annotations that are available in Spring Boot with examples.


1) @SpringBootApplication : The main class has @springBootApplication annotation. It simply invokes the springApplication.run method. This starts the Spring application as a standalone application, runs the embedded servers and loads the beans. @springBootApplication combines three annotations.
  • @EnableAutoConfiguration
  • @Configuration
  • @ComponentScan  

Example : 

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringApplicationMain 

           public static void main(String[] args) {
                
               SpringApplication.run(SpringApplication.class, args);
       }
}

2) @EnableAutoConfiguration : @EnableAutoConfiguration is an annotation in the Spring Framework that enables automatic configuration of beans and components in a Spring Boot application.
When you annotate your main class with @EnableAutoConfiguration, Spring Boot performs classpath scanning to detect and configure beans based on the dependencies present in your project.

Example : 

@EnableAutoConfiguration 
@Configuration
public class SpringApplicationMain {

        public static void main(String[] args) {       
       SpringApplication.run(SpringApplication.class,args);
   }      
}


3) @Configuration : When you annotate a class with @Configuration, Spring treats it as a source of bean definitions and other configuration options. It allows you to define and customize beans, configure various Spring features, and specify dependencies between beans.

Example : 

@EnableAutoConfiguration 
@Configuration
public class SpringApplicationMain {

        public static void main(String[] args) {       
       SpringApplication.run(SpringApplication.class,args);
   }      
}

4) ComponentScan : The @ComponentScan annotation is used in the Spring Framework to enable component scanning for automatic bean detection and registration. It tells Spring where to look for components, such as @Component, @Service, @Repository, and @Controller, so that they can be automatically instantiated and managed by the Spring container.

Example : 

@ComponentScan
@Configuration
public class SpringApplicationMain {

        public static void main(String[] args) {
       SpringApplication.run(SpringApplication.class,args);
   }      
}


5) @Autowired : The @Autowired annotation is used in the Spring Framework for automatic dependency injection. It allows Spring to automatically wire dependencies into a class, eliminating the need for manual wiring or explicit configuration.

Example : 

@Service
public class SpringService {

        @Autowired
        private Repository repository;

        public void serviceCall() {
        repository.callDatabase(argument);  

   }      
}

6) @RestController and @Controller : @RestController and @Controller are annotations in the Spring Framework that are used to define classes as controllers in a Spring MVC (Model-View-Controller) application.

  • @RestController : The @RestController annotation is a specialized version of the @Controller annotation. It is typically used to define RESTful web services or APIs. @RestController annotation combines @Controller and @ResponseBody annotation. Thus, it automatically applies @ResponseBody to all methods inside controller class.
            
        Example : 
                        
                        @RestController
                         @RequestMapping("/api")   
                        public class SpringController {
                          
                          @Getmapping("/name")  
                          public string getName() {          
                          return "ram";                  
                      }
                   }

Flow Diagram of Rest Controller : 

          HttpRequest
client -------------------> Dispatcher servlet -------> Handler Mapping -------> REST Controller--------------> Response.
                                                                                                             


  • @Controller : When you annotate a class with @Controller, it indicates that the class serves as a controller that handles HTTP requests and generates responses. In case of controller we need to explicitly define the response body.
         Example : 
         
                       @Controller
                        @RequestMapping("/api")   
                        public class SpringController {
                          
                          @Getmapping("/name")  
                          public @ResponseBody getName() {          
                          return "ram";                  
                      }
                 }

Flow Diagram of Controller : 
 
Client ---> HttpRequest---> Dispatcher Servlet----> HandlerMapping --->Controller ----> ResponseBody----->Response.
 


7) @Service : The @Service annotation is used in the Spring Framework to indicate that a class is a service component. It is typically used to define classes that provide business logic or perform services within an application.  In short @Service annotation used at implementation layer of application.

Example : 
 
@Service
public class SpringServiceImpl {

        @Autowired
        private Repository repository;

        public void serviceCall() {

        repository.callDatabase(argument);  

   }      
}

8) @Repository: The @Repository annotation is used in the Spring Framework to indicate that a class is a repository component. It is typically used to define classes that interact with a database or external data source, providing data access and persistence operations. It also indicate the class provides the mechanism of insert, update, delete, save, retrieval and search. It is used at DOA layer of application.

Example : 

@Repository
public class SpringRepository {

         //save data in database layer (DOA layer)
        public void save() {

   }      
}

9) @Component: It allows spring to detect the bean automatically. In Other word we can say that without writing explicit code of creation of object , Spring will scan our application for classes annotated with @Component. Instantiate them and inject any specified dependencies into them. Spring automatically create the instance and manage it.

Example : 

@Component
public class SpringApplication {

}


10) @Lazy : The bean which has been declared with @Lazy annotation will not be initialized by spring container during start-up/bootstrapping of the application context. This is concept of Lazy initialization which allows you to create the object when it is needed. This annotation is marked at object level. When your bean is involving large objects like holding large amount of data from database, it is not good to keep such large data object ready in memory till its use so @Lazy annotation can help to save the application speed up your application from large object initialization.

Example : 

@Component
@Lazy
public class SpringApplicationBean {

}
           
11) @Qualifier :  @Qualifier annotation is used to resolve the duplication of multiple beans of same type are available for autowiring. It helps to specify which beans should injected. So you can use @Qualifier annotation with @Autowired annotation to resolve the confusion.

Example : 

@Component
public class  SpringUser{

    @Autowired
    @Qualifier("beanQualifier1")
    private SpringInterface springInterface;
    
    // Use the injected bean
    @Autowired
    @Qualifier("beanQualifier2")
    private SpringInterface springInterface;
}

12) @Inject : It allows Spring to automatically wire dependencies into a class. @Inject annotation works similar as @Autowired annotation , only difference is @Inject annotation introduced in Java 6 not in spring framework. Default scope of inject beans is prototype.

Example : 

@Service
public class SpringService {

        @Inject
        private Repository repository;

        public void serviceCall() {
        repository.callDatabase(argument);  

   }      
}

13) @Primary : @Primary annotation is provided by spring framework. When you have multiple beans of same type @Primary annotation used to provide which beans should given a higher proirity.

Example :

@Configuration
public class SpringApplicationConfig {
  
    @Bean
    @Primary
    public Person boy() {
        return new Boy();
    }
  
    @Bean
    public Person girl() {
        return new Girl();
    }
}

14) @Override : @Override annotation is used to indicate that method of subclass(Child class) is intended to override the method of superclass (Parent class).

Example :

class Parent {
    public void property() {
        System.out.println("The animal makes a sound.");
    }
}

class Child extends Parent {
    @Override
    public void property() {
        System.out.println("The dog barks.");
    }
}

15) @Slf4j : This annotation is used to write the log statements in your code. It also provides a common interface for various logging frameworks such as Logback, Log4j, and java.util.logging. 
Steps to use @Slf4j annotation
  • Add @Slf4j annotation at class level
  • Declare logger instance using LoggerFactory.
 private static final Logger logger = LoggerFactory.getLogger(YourClassName.class);
  • add logger statements in your code i.e logger.info("hello world");

16) @CrossOrigin : Cross-Origin Resource Sharing (CORS) is a security concept that allows restricting the resources implemented in web browsers. It can be added at particular controller or handler method. It allows to make requests only in same domain.

Example : 

                       @RestController
                        @CrossOrigin(origins: "url")

                        @RequestMapping("/api")   
                        public class SpringController {
                          
                          @Getmapping("/name")  
                          public string getName() {          
                          return "ram";                  
                      }
                   }

17) @RestControllerAdvise : The @RestControllerAdvice annotation is used in the Spring Framework to define a global exception handler for RESTful APIs. It combines the functionality of @ControllerAdvice and @ResponseBody annotations. when we use this @RestControllerAdvise gives advise to all RestController and handle global exception for REST API.

Example : 

@RestControllerAdvice
public class ControlleradviseException {
  
  @ExceptionHandler(value = {DataNotFoundException.class})
  @ResponseStatus(value = HttpStatus.NOT_FOUND)
  public ErrorMessage DataNotFoundException() {
}


SUMMARY 

We have covered all annotations require for spring project. Next we are covering Hibernate annotations for spring boot project.

About us
I am software developer in IT Industry

Contact us
surajladda07@gmail.com