Spring Boot HandBook

    Commonly used Spring boot annotations

    Spring Boot simplifies the process of building applications by providing a wide range of annotations that help developers quickly configure and implement various features. Below, we will explore some of the most commonly used Spring Boot annotations, along with examples to demonstrate their usage.

    1. @SpringBootApplication#

    Explanation:#

    @SpringBootApplication is the cornerstone annotation of any Spring Boot application. It is a convenience annotation that combines three other annotations: @SpringBootConfiguration, @EnableAutoConfiguration, and @ComponentScan. This annotation marks the main class of a Spring Boot application and triggers the auto-configuration, component scanning, and other Spring Boot features.

    Usage Example:#

    import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } }

    Explanation:

    In the example above, @SpringBootApplication is applied to the main class MyApplication. This annotation enables the auto-configuration, scans the components within the package, and configures the application context, making it a fully functional Spring Boot application.

    2. @RestController#

    Explanation:#

    @RestController is used to create RESTful web services in Spring Boot. It is a combination of @Controller and @ResponseBody. This annotation indicates that the class's methods should return JSON or XML responses directly, bypassing the need for view resolution.

    Usage Example:#

    import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class GreetingController { @GetMapping("/greeting") public String greet() { return "Hello, World!"; } }

    Explanation:

    In this example, @RestController is applied to the GreetingController class. The greet() method is mapped to the /greeting endpoint using @GetMapping, and it returns a simple string. Since it's a REST controller, the response is automatically converted to JSON format.

    3. @Autowired#

    Explanation:#

    @Autowired is used to inject dependencies automatically. It can be applied to fields, constructors, or setter methods. Spring Boot will automatically resolve and inject the appropriate bean into the annotated field or method.

    Usage Example:#

    import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class GreetingService { public String getGreeting() { return "Hello, World!"; } } import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class GreetingController { @Autowired private GreetingService greetingService; @GetMapping("/greet") public String greet() { return greetingService.getGreeting(); } }

    Explanation:

    In the example above, @Autowired is used to inject the GreetingService bean into the GreetingController. The greet() method calls the getGreeting() method from the GreetingService class to return the greeting message.

    4. @Component#

    Explanation:#

    @Component is a generic stereotype annotation used to mark a class as a Spring-managed component. Classes annotated with @Component are automatically detected and registered as beans by Spring’s component scanning.

    Usage Example:#

    import org.springframework.stereotype.Component; @Component public class MyComponent { public void performTask() { System.out.println("Task performed!"); } }

    Explanation:

    In this example, the MyComponent class is annotated with @Component. This makes it a Spring-managed bean, and it can be injected into other components using @Autowired.

    5. @Service#

    Explanation:#

    @Service is a specialization of @Component and is used to mark a class as a service provider. This annotation indicates that the class contains business logic.

    Usage Example:#

    import org.springframework.stereotype.Service; @Service public class CalculationService { public int add(int a, int b) { return a + b; } }

    Explanation:

    The CalculationService class is annotated with @Service, indicating that it provides business logic (in this case, adding two numbers). This class can be injected into controllers or other services.

    6. @Repository#

    Explanation:#

    @Repository is another specialization of @Component, typically used to indicate that a class is a Data Access Object (DAO). It also provides exception translation, converting database-related exceptions into Spring’s DataAccessException.

    Usage Example:#

    import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface UserRepository extends JpaRepository<User, Long> { // Custom query methods can be added here }

    Explanation:

    Here, UserRepository is a repository interface that extends JpaRepository, and it’s annotated with @Repository. This annotation makes it a Spring bean, and the repository can be injected into other components.

    7. @Configuration#

    Explanation:#

    @Configuration indicates that a class contains Spring configuration. It is used to define beans and configure dependencies within the Spring context.

    Usage Example:#

    import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class AppConfig { @Bean public MyService myService() { return new MyService(); } }

    Explanation:

    In this example, AppConfig is annotated with @Configuration, indicating that it contains Spring configuration. The myService() method is annotated with @Bean, which tells Spring to manage the MyService instance as a bean.

    8. @Value#

    Explanation:#

    @Value is used to inject values into fields from properties files or environment variables. This annotation helps to externalize configuration.

    Usage Example:#

    import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class MyComponent { @Value("${app.name}") private String appName; public void printAppName() { System.out.println("Application Name: " + appName); } }

    Explanation:

    In this example, the appName field in MyComponent is injected with the value of app.name from the application.properties file using @Value.

    9. @RequestMapping#

    Explanation:#

    @RequestMapping is used to map HTTP requests to handler methods in Spring MVC and REST controllers. It can be used at both the class level and the method level.

    Usage Example:#

    import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api") public class ApiController { @RequestMapping("/hello") public String sayHello() { return "Hello, API!"; } }

    Explanation:

    In this example, @RequestMapping is used at the class level to map /api to the ApiController. At the method level, it maps /hello to the sayHello() method, which will be triggered by HTTP requests to /api/hello.

    10. @GetMapping, @PostMapping, @PutMapping, @DeleteMapping#

    Explanation:#

    These annotations are shortcuts for @RequestMapping for specific HTTP methods: GET, POST, PUT, and DELETE. They are used to map requests to handler methods.

    Usage Example:#

    import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { @GetMapping("/user") public String getUser() { return "Fetching user"; } @PostMapping("/user") public String createUser() { return "Creating user"; } }

    Explanation:

    Here, @GetMapping maps GET requests to /user to the getUser() method, while @PostMapping maps POST requests to /user to the createUser() method.

    11. @ConditionalOnProperty#

    Explanation:#

    @ConditionalOnProperty is an annotation used in Spring Boot to conditionally include a bean or configuration based on the presence and value of a specific property in the application's configuration file (e.g., application.properties or application.yml). This annotation is particularly useful for enabling or disabling features based on configuration settings.

    Attributes:#

    • prefix: The prefix of the property to check.
    • name: The name of the property to check.
    • havingValue: The expected value of the property. The bean will be created only if the property has this value.
    • matchIfMissing: If set to true, the bean will be created even if the property is missing, provided all other conditions match.

    Usage Example:#

    import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class MyFeatureConfig { @Bean @ConditionalOnProperty(name = "feature.enabled", havingValue = "true") public MyFeatureService myFeatureService() { return new MyFeatureService(); } }

    Example Configuration:#

    # application.properties feature.enabled=true

    Explanation:

    In this example, the MyFeatureService bean will only be created if the feature.enabled property is set to true in the application.properties file. The @ConditionalOnProperty annotation checks the value of feature.enabled, and if it matches the expected value (true), the bean is registered in the Spring context. If feature.enabled is false or absent, the bean will not be created.

    Common Use Cases:#

    • Feature Toggles: Enable or disable certain features in your application based on configuration.
    • Environment-Specific Beans: Configure beans that should only be active in certain environments (e.g., development, production).
    • External Integrations: Conditionally enable beans that integrate with external systems or services based on whether the integration is enabled in the configuration.

    In this article, we explored some of the most commonly used annotations in Spring Boot, including @SpringBootApplication, @RestController, @Autowired, @Component, @Service, @Repository, @Configuration, @Value, @RequestMapping, and specialized HTTP mapping annotations like @GetMapping and @PostMapping. We also introduced the @ConditionalOnProperty annotation, which allows for conditional bean creation based on application configuration. By understanding and utilizing these annotations, developers can significantly enhance their productivity and build more efficient and maintainable Spring Boot applications.

    Last updated on Oct 13, 2024