annotations in spring boot

2. Advance annotations in spring boot – Tested

Advance annotations IN Spring boot

Advanced annotations in spring boot often involve more specialized use cases and fine-grained control over various aspects of your Spring Boot application. These annotations are typically used in specific scenarios or for customizing the behavior of your application.

Here are some advanced annotations in spring boot:

@Component @Service@Repository@PropertySource
@Autowired@Qualifier@Value@Profile
@Inject@Bean@Configuration@SpringBootTest
@Conditional@Lazy@Value@Transactional
@EntityScan@EnableWebSecurity@Secured@PreAuthorize
@EnableAutoConfiguration@SpringBootConfiguration@Valid@NotNull
@NotEmpty@NotBlank@Size@Min
@RestControllerAdvice@ExceptionHandler@ResponseStatus@Custom Validation Annotations
Spring Boot Annotations

1. @Component

  • @Component is a stereotype annotations in spring boot that indicates a class should be treated as a Spring bean.
  • Spring Boot scans for classes marked with @Component during the component scanning phase.
  • It creates instances of these classes as beans and registers them in the Spring application context.

Suppose you have a simple annotations in Spring Boot application with a Person class and you want to mark it as a Spring bean using @Component.

import org.springframework.stereotype.Component;

@Component // Marking the class as a Spring bean
public class Person {
    private String name;
    private int age;

    // Constructors, getters, and setters

    // toString
}

In your main application class, you can use the @SpringBootApplication annotation to enable component scanning and include the Person bean in your Spring application context:

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

@SpringBootApplication
public class MyApp {

    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(MyApp.class, args);

        // Retrieve the Person bean from the application context
        Person person = context.getBean(Person.class);

        // Use the Person bean
        person.setName("John");
        person.setAge(30);

        System.out.println(person); // Output: Person [name=John, age=30]
    }
}

In this example, the Person class is marked with @Component, making it a Spring bean. During application startup, Spring Boot scans for components and creates an instance of Person, which can be retrieved from the application context and used within the application.


2. @Service

@Service annotation is part of the Spring Framework’s stereotype annotations, and it indicates that a class is a service component. Service components are intended to hold the business logic of your application.

Example: Let’s say you are building a simple Spring Boot application for a library management system, and you want to create a service that manages books. You can use the @Service annotation to define a BookService class:

@Service
public class BookService {
    // methods for operations

}

In this example:

  • The @Service annotations in spring boot marks the BookService class as a service component.
  • The BookService class defines methods for performing various operations related to books, such as getting all books, retrieving a book by ID, adding a book, and deleting a book.

With this setup, you can easily use the BookService in your controllers or other parts of your Spring Boot application to perform book-related operations. The Spring framework will handle the instantiation and management of the BookService bean, and you can focus on writing the business logic.


3. @Repository

The @Repository annotations in spring boot is used to indicate that a class is a Data Access Object (DAO) or repository. It is typically applied to classes that interact with a database or any other form of data storage, allowing Spring to manage them as Spring beans. This annotations in spring boot helps in the automatic generation of Spring beans for your data access layer, simplifying database operations and exception handling.

@Repository
public class UserRepository {
    // Data access methods and queries go here
}

In this example, the UserRepository class is marked with the @Repository annotation. This indicates to Spring that this class should be managed as a Spring bean and is responsible for data access operations, typically related to users in this case.

When you use the @Repository annotation, Spring Boot provides several benefits:

  1. Automatic Bean Registration: Spring Boot scans the classpath for components, including classes annotated with @Repository, and automatically registers them as Spring beans.
  2. Exception Translation: Spring Boot also provides exception translation for database-related exceptions. For example, it translates JDBC SQLExceptions into Spring’s DataAccessException hierarchy, making error handling more convenient.
  3. Transaction Management: Spring Boot can automatically manage transactions for methods in the repository, ensuring that they are executed within a transactional context.
  4. Simplifies Testing: You can easily test your data access layer by using Spring’s testing support, which provides tools for creating mock repositories or using embedded databases.

4. @PropertySource & @Value

The @PropertySource annotations in Spring Boot is used to specify the location of external property files that should be loaded into the Spring Environment. These property files can contain configuration settings such as database connection details, application-specific settings, or any other key-value pairs that your Spring application needs.

Annotate Your Configuration Class: You typically use @PropertySource in combination with a configuration class to specify the location of your property files. For example:

@Configuration
@PropertySource("classpath:application.properties")
public class AppConfig {
    // Your configuration code here
}

In this example, we’ve annotated the AppConfig class with @PropertySource and specified that it should load properties from a file named application.properties located on the classpath.

Access Properties: Once you’ve configured the @PropertySource, you can access the properties in your Spring components, such as beans or services, using the @Value annotation or by injecting the Environment object.

@Component
public class MyService {
    @Value("${my.property}")
    private String myProperty;

    // Your service logic here
}

In this example, we’ve injected the value of the my.property key from the application.properties file into the myProperty field of the MyService bean.

Create the Property File: You need to create the property file you specified in the @PropertySource annotation. In this case, you should have an application.properties file with your key-value pairs:

my.property=Hello, Spring Boot!

Now, when you run your Spring Boot application, it will load the properties from the specified property file, making them available for use in your application components. The


5. @Autowired

The @Autowired annotations in Spring Boot is used to automatically inject dependencies into a class, making it easier to manage and use external components, such as services or repositories, within your application. It minimizes the need for explicit object creation and wiring, enhancing code readability and maintainability.

Dependency Injection: When you annotate a field, constructor, or method with @Autowired, Spring Boot looks for a compatible bean of the required type and injects it automatically. This is typically used for injecting dependencies like services, repositories, or other Spring components into your classes.

Example: Suppose you have a Spring Boot application and you want to inject a UserService into a controller class. Here’s how you can do it:

@Service
public class UserService {
    // ...
}
@RestController
public class UserController {
    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }
    // ... Your controller methods that use userService
}

6. @Qualifier

  • @Qualifier is annotations in spring boot used to disambiguate dependencies when there are multiple beans of the same type.
  • It helps Spring to determine which specific bean should be injected into a particular dependency.
  • You specify the name (or value) of the bean you want to inject by using the @Qualifier annotation.

Example:

Let’s say you have two implementations of an interface called PaymentService in your Spring Boot application:

<div tabindex="0">public interface PaymentService {</div><div tabindex="0">    void processPayment();</div><div tabindex="0">}</div><div tabindex="0"></div><div tabindex="0"></div>
@Service("creditCardPayment")
public class CreditCardPaymentService implements PaymentService {
    @Override
    public void processPayment() {
        System.out.println("Processing credit card payment.");
    }
}
@Service("paypalPayment")
public class PayPalPaymentService implements PaymentService {
    @Override
    public void processPayment() {
        System.out.println("Processing PayPal payment.");
    }
}

In your application, you want to inject one of these services into another component. You can use @Qualifier to specify which implementation you want to use:

@Service
public class OrderService {
    private final PaymentService paymentService;

    @Autowired
    public OrderService(@Qualifier("creditCardPayment") PaymentService paymentService) {
        this.paymentService = paymentService;
    }

    public void processOrder() {
        paymentService.processPayment();
    }
}

In this example, the OrderService uses @Qualifier("creditCardPayment") to indicate that it wants to inject the CreditCardPaymentService specifically, even though there are multiple PaymentService implementations available. If you don’t specify @Qualifier, Spring may not know which bean to inject and may throw an error due to ambiguity.When you create an instance of OrderService, Spring will inject the CreditCardPaymentService into it, and calling processOrder() will result in “Processing credit card payment.” being printed.


7. @Profile

The @Profile annotations in Spring Boot is used to specify the environment or configuration profiles in which a particular component or bean should be active. This annotations in spring boot allows you to conditionally include or exclude beans based on the active profile(s) set in your annotations in Spring Boot application. It’s a powerful way to manage configuration and component selection for different deployment environments (e.g., dev (Development), qa (Testing), prod (Production).

Here’s a short description and an example of how to use @Profile in Spring Boot:

Defining Profiles: In Spring Boot, you can define profiles in various ways, such as in application.properties or application.yml:

#application.properties
spring.profiles.active=dev
#application.yml
spring:
  profiles:
    active: dev

Annotating Components:

You can annotate components (beans) with @Profile to indicate in which profiles they should be active. Here’s an example:

@Configuration
public class MyConfig {

    @Bean
    @Profile("dev")
    public DataSource devDataSource() {
        return new DataSource("jdbc:mysql://localhost/devdb", "devuser", "devpassword");
    }

    @Bean
    @Profile("prod")
    public DataSource prodDataSource() {
        return new DataSource("jdbc:mysql://localhost/proddb", "produser", "prodpassword");
    }
}

In this example, two DataSource beans are defined, each annotated with @Profile. The devDataSource bean will be active only when the “dev” profile is active, and the prodDataSource bean will be active when the “prod” profile is active.

Activating Profiles: You can activate profiles in various ways, as mentioned in step 1. Profiles can also be activated programmatically using the SpringApplication class:

@SpringBootApplication
public class MyApplication {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(MyApplication.class);
        app.setAdditionalProfiles("prod"); // Activate the "prod" profile
        app.run(args);
    }
}
  1. In this example, the “prod” profile is explicitly activated when running the Spring Boot application.

With the @Profile annotation, you can control which beans are created and made available based on the active profiles, making it easier to manage different configurations for different environments in your Spring Boot application.

8. @Inject

In Spring Boot, the @Inject annotations in spring boot is not a native Spring annotation; instead, it is typically associated with the Java Dependency Injection framework called “javax.inject” (JSR-330). Spring Boot itself primarily uses annotations in spring boot like @Autowired and @Qualifier for dependency injection. However, you can still use @Inject in Spring Boot if you include the necessary dependencies.

Example in Spring Boot: Let’s say you have a simple Spring Boot service that provides user-related functionality, and you want to inject a UserRepository bean into the service class using the @Inject annotations in spring boot.

<dependency>
    <groupId>javax.inject</groupId>
    <artifactId>javax.inject</artifactId>
    <version>1</version>
</dependency>
@Service
public class UserService {
    private final UserRepository userRepository;
    @Inject
    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }
    // ... rest of the service methods using userRepository ...
}

In this example, the @Inject annotations in spring boot is used on the constructor to indicate that the UserRepository dependency should be injected into the UserService bean. You would need to ensure that the javax.inject and Spring Boot dependencies are correctly configured in your project for this to work.


9. @Bean

The @Bean annotations in spring boot is used to define a method as a bean definition. Beans are objects managed by the Spring container (also known as the Spring Application Context) that provide various services within your application. When you annotate a method with @Bean, Spring will execute that method to create an instance of the bean and manage its lifecycle. This is often used for defining custom beans that are not automatically configured by Spring Boot.

Example: Create a Java class and annotate it with @Configuration. This annotations in spring boot indicates that the class contains bean definitions.

@Configuration
public class MyConfiguration {
    
    @Bean
    public MyService myService() {
        return new MyService();
    }
}

In the example above, MyService is a custom class you want to configure as a Spring bean. By annotating the myService() method with @Bean, you are telling Spring to manage the lifecycle of the MyService bean. When you need to use this bean elsewhere in your application, you can simply inject it using @Autowired or retrieve it from the Spring context.

For example, you can inject the MyService bean into another class like this:

@Service
public class MyOtherService {
    
    private final MyService myService;
    
    @Autowired
    public MyOtherService(MyService myService) {
        this.myService = myService;
    }
    
    // ...
}

In this way, Spring Boot manages the creation and injection of beans, allowing you to use them throughout your application with proper dependency injection.


10. @Configuration

@Configuration is an annotations in spring boot for Java that is used to declare and configure various components and settings in a Spring application. It is typically applied to Java classes and methods to specify how Spring should manage and configure beans and other resources.

Example:

@Configuration
public class AppConfig {

    @Bean
    public MyService myService() {
        return new MyServiceImpl();
    }

    @Bean
    public DataSource dataSource() {
        // Configure and return a DataSource bean
        return new DriverManagerDataSource("jdbc:mysql://localhost:3306/mydb", "username", "password");
    }
}

In this example:

  1. The @Configuration annotations in spring boot is applied to the AppConfig class, indicating that it contains bean configuration settings.
  2. Two bean definition methods are annotated with @Bean. These methods define beans, such as myService() and dataSource(). Spring will manage these beans, and their instances will be available for injection into other parts of the application.
  3. Inside the dataSource() method, you can see that we configure and create a DataSource bean using the DriverManagerDataSource class. Spring will manage this bean’s lifecycle and provide it to other parts of the application when needed.

Overall, the @Configuration annotation is crucial in Spring for defining and organizing bean configurations in a concise and structured manner.


11. @SpringBootTest

  • @SpringBootTest loads the complete Spring application context, including all the beans and configurations.
  • It allows you to perform integration tests, which test the interactions between different components of your application.
  • You can use it to test your application’s HTTP endpoints, service layers, and other parts of your Spring Boot application.

Example: Let’s say you have a simple Spring Boot application with a RESTful endpoint, and you want to write a test for that endpoint using @SpringBootTest. Here’s an example:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MyControllerIntegrationTest {

    @LocalServerPort
    private int port;

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    public void testHelloEndpoint() throws Exception {
        String url = "http://localhost:" + port + "/hello";
        String response = restTemplate.getForObject(url, String.class);
        assertThat(response).contains("Hello, World!");
    }
}

In this example:

  • @SpringBootTest annotations in Spring Boot is used to load the complete Spring application context.
  • @LocalServerPort annotations in spring boot inject the random port that the embedded web server is running on.
  • @Autowired annotations in Spring Boot is used to inject a TestRestTemplate, which you can use to make HTTP requests to your application.
  • The testHelloEndpoint method tests the “/hello” endpoint by making an HTTP GET request and checking the response content.

This is just a basic example, but @SpringBootTest annotations in spring boot can be used for more complex integration testing scenarios where you want to test various parts of your Spring Boot application in a real, integrated environment.


12. @Conditional

In Spring Boot, the @Conditional annotation is used to conditionally configure beans based on certain conditions. This annotation allows you to control the instantiation of beans depending on whether specific conditions are met. It’s particularly useful when you want to have different configurations for your application based on various factors.

@Conditional is an annotation used in Spring Boot to conditionally create beans based on specified conditions. It provides a way to dynamically configure the application context by evaluating conditions during the bean creation process.

Example:

Suppose you want to create a bean only if a certain property is defined in your application’s configuration. You can use @Conditional in combination with a custom condition class to achieve this:

@Configuration
public class MyConfiguration {

    @Bean
    @ConditionalOnProperty(name = "myapp.feature.enabled", havingValue = "true")
    public MyBean myBean() {
        return new MyBean();
    }
}

In this example

the MyBean bean will only be created if the property myapp.feature.enabled is defined in your application’s properties or YAML configuration files and its value is set to true. If the condition is not met, the bean won’t be created.

This is just one of many use cases for @Conditional. You can create custom conditions or use built-in conditions provided by Spring Boot to control bean creation based on various factors like environment properties, class availability, etc.


13. @Lazy

In Spring Boot, the @Lazy annotation is used to specify that a bean should be lazily initialized. This means the bean will only be created when it is first requested, rather than during the application’s startup phase. Lazy initialization can help improve application startup time and reduce resource consumption.

@Lazy is an annotations in Spring Boot that allows you to control the initialization behavior of a bean. When you annotate a bean definition with @Lazy, Spring Boot will create and initialize the bean only when it is first used, rather than eagerly initializing it during application startup.

Example: Suppose you have a Spring Boot application where you want to lazily initialize a service bean. Here’s how you can use @Lazy:

@Lazy
public class MyLazyService {
    // Service logic
}

In this example

the MyLazyService bean will be lazily initialized. It won’t be created during the application’s startup process. Instead, it will be instantiated and initialized only when it’s first requested, such as when it’s injected into another component or service. This can be particularly useful for optimizing the startup performance of your Spring Boot application when you have beans that are not needed immediately upon application launch.


14. @ComponentScan

@ComponentScan is a Spring Framework annotations in Spring Boot used applications to specify the base package(s) where Spring should look for components like @Component, @Service, @Repository, and other Spring-managed beans. It tells Spring where to scan for these components to automatically register them as Spring beans in the application context.

  • @ComponentScan is used to enable component scanning in your Spring Boot application.
  • It searches for components in the specified package and its sub-packages.
  • Spring Boot automatically performs component scanning on the package where the main application class is located (the class annotated with @SpringBootApplication), but you can use @ComponentScan to specify additional packages or override the default behavior.

Example: Let’s say you have a Spring Boot project with the following package structure:

In this example

the MyApplication class is the main application class annotated with @SpringBootApplication. By default, Spring Boot scans the com.example.myapp package and its sub-packages for components.

You can use @ComponentScan to specify additional packages to scan, like the services and repositories packages:

@ComponentScan(basePackages = {"com.example.myapp.services", "com.example.myapp.repositories"})
public class MyApplication {

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

By adding @ComponentScan with the specified package names, Spring Boot will now scan the com.example.myapp.services and com.example.myapp.repositories packages for components in addition to the default package. This ensures that Spring manages beans from these packages as well, making them available for injection and other Spring-related functionalities.

15. @Transactional

@Transactional is an annotations in Spring boot that is commonly used in Spring Boot applications to manage database transactions. It indicates that a method should be executed within a database transaction context. If the method succeeds, the changes are committed to the database, and if an exception is thrown, the changes are rolled back, ensuring data consistency.


@Service
public class UserService {

    private final UserRepository userRepository;

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Transactional
    public void createUser(User user) {
        // Perform some database operations, like saving the user
        userRepository.save(user);
    }

    @Transactional(readOnly = true)
    public User getUserById(Long userId) {
        // Retrieve a user from the database
        return userRepository.findById(userId).orElse(null);
    }

    @Transactional
    public void updateUser(User updatedUser) {
        // Update user information in the database
        userRepository.save(updatedUser);
    }

    @Transactional
    public void deleteUser(Long userId) {
        // Delete a user from the database
        userRepository.deleteById(userId);
    }
}

In this example:

  1. The @Transactional annotation is used on methods that interact with the database. In the createUser, updateUser, and deleteUser methods, it ensures that the database operations are executed within a single transaction, and changes are committed or rolled back appropriately.
  2. The readOnly attribute is set to true for the getUserById method. This indicates that this method is read-only and does not modify the database. Using readOnly can provide certain performance optimizations.
  3. The UserService class is marked as a Spring service using @Service, which allows it to be managed by the Spring container.

By using @Transactional, you can simplify your code and let Spring handle the transaction management for you, ensuring the integrity of your database operations.


16. @EntityScan

In Spring Boot, @EntityScan is an annotation used to specify the base packages that Spring should scan for JPA (Java Persistence API) entity classes. Entity classes are typically used to represent database tables in your application.

@EntityScan allows you to customize the package scanning behavior of Spring Boot’s JPA auto-configuration. By default, Spring Boot scans for entity classes in the package where your main application class is located and its sub-packages. If your entity classes are located in different packages, you can use @EntityScan to explicitly specify the packages to be scanned for entities.

Example:

The User and Product classes are JPA entity classes, and Application.java is your main application class. To specify that Spring Boot should scan the com.example.entities package for entity classes, you can use @EntityScan as follows:

@SpringBootApplication
@EntityScan(basePackages = "com.example.entities")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

In this example, @EntityScan(basePackages = "com.example.entities") tells Spring Boot to scan the com.example.entities package and its sub-packages for JPA entity classes during its auto-configuration process.

This customization is particularly useful when you have entity classes spread across multiple packages in your Spring Boot application.


17. @EnableWebSecurity

In Spring Boot, the @EnableWebSecurity annotation is used to enable and configure Spring Security in your application. Spring Security is a powerful framework for handling authentication and authorization in web applications.

The @EnableWebSecurity annotation is typically placed on a configuration class to indicate that it should be used to configure Spring Security for your application. It tells Spring Boot to enable the default Spring Security configuration and allows you to customize it further using methods within the annotated configuration class.

Example:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/", "/home").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("user").password("{noop}password").roles("USER")
                .and()
                .withUser("admin").password("{noop}adminpassword").roles("USER", "ADMIN");
    }
}
  1. In this example, we have created a SecurityConfig class annotated with @Configuration and @EnableWebSecurity. This class extends WebSecurityConfigurerAdapter to provide custom security configurations.1
    • The configure(HttpSecurity http) method configures URL-based security rules. In this case, we’ve specified that the home page (/ and /home) should be accessible without authentication, and any other request should require authentication. We’ve also configured a custom login page and allowed logout.
    • The configure(AuthenticationManagerBuilder auth) method configures authentication. We’ve used in-memory authentication with two users (user and admin) and their respective passwords and roles.

Please note that this is a basic example, and in a real-world application, you might use a database for user authentication, customize security settings further, and configure other aspects of Spring Security to suit your specific requirements.


18. @Secured

annotations in Spring Boot, the @Secured annotation is used to apply method-level security to control access to specific methods in a Spring application. It is part of the Spring Security framework, which provides comprehensive security features for your application.

The @Secured annotation is used to specify which roles or authorities are allowed to access a particular method. It is often used in conjunction with method-level security provided by Spring Security. When a method is annotated with @Secured, Spring Security checks the user’s roles or authorities before allowing access to the method. If the user has the required roles or authorities, they can invoke the method; otherwise, access is denied.

Example

Suppose you have a Spring Boot application with Spring Security configured, and you want to secure a method that allows only users with the role “ROLE_ADMIN” to access it. Here’s how you can use the @Secured annotation:


@Service
public class MyService {

    // This method can only be accessed by users with the role "ROLE_ADMIN"
    @Secured("ROLE_ADMIN")
    public void adminOnlyMethod() {
        // Method logic here
    }

}

In this example, the adminOnlyMethod is annotated with @Secured("ROLE_ADMIN"), which means only users who have the “ROLE_ADMIN” authority will be allowed to invoke this method. If a user without the “ROLE_ADMIN” authority tries to access this method, they will receive a security exception.

To make this annotation work, you need to configure Spring Security with the appropriate roles and authorities for your application users. Typically, you define user roles and configure access rules in your security configuration class or XML configuration.


19. @PreAuthorize

The @PreAuthorize annotation is a part of the Spring Security framework in Spring Boot that allows you to specify access control rules for methods in your application. It is used to enforce method-level security based on expressions that define who can access a particular method. those annotations in Spring Boot are commonly used in conjunction with other Spring Security features like authentication and authorization.

Annotation Usage

You can apply the @PreAuthorize annotation to methods in your Spring Boot application’s controllers or services. The annotation takes a SpEL (Spring Expression Language) expression as its value, which defines the access control rules for the method.

Example

Let’s say you have a Spring Boot application with a RESTful controller that manages user data. You want to restrict access to a method getUserDetails to only users who have the “ROLE_ADMIN” authority. You can use the @PreAuthorize annotation to achieve this:


@RestController
public class UserController {

    // This method can only be accessed by users with "ROLE_ADMIN" authority.
    @GetMapping("/users/{userId}")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public User getUserDetails(@PathVariable Long userId) {
        // Implementation to fetch and return user details
        // ...
    }

    // Other methods in the controller
}

In the above example, the @PreAuthorize annotation is used to specify that the getUserDetails method can only be accessed by users who have the “ROLE_ADMIN” authority. If a user does not have this authority, they will receive an access denied error when trying to access this method.

Note that you need to configure Spring Security properly in your Spring Boot application to make these annotations in Spring Boot work as expected. This typically involves setting up authentication providers, defining user roles, and configuring access control rules.


20. @EnableAutoConfiguration

In Spring Boot, the @EnableAutoConfiguration annotation is a powerful and convenient feature that automatically configures your application based on its classpath and the dependencies you’ve added. It is part of Spring Boot’s auto-configuration mechanism, which aims to reduce the need for explicit configuration and make it easier to get started with Spring Boot applications.

The @EnableAutoConfiguration annotation tells Spring Boot to automatically configure the Spring application context by scanning the classpath for certain predefined classes and configuration properties. Spring Boot will configure beans, database connections, messaging systems, and other components based on the libraries and dependencies it detects in your project.

Example

Let’s say you’re building a Spring Boot web application that uses a database. If you add the spring-boot-starter-data-jpa dependency to your project, Spring Boot will automatically configure a DataSource, a JPA EntityManager, and other necessary components for working with a database. You don’t need to write extensive configuration files for these components; Spring Boot handles it for you.


@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan
public class MySpringBootApplication {
    public static void main(String[] args) {
        SpringApplication.run(MySpringBootApplication.class, args);
    }
}
  • In this example, @SpringBootApplication is a convenience annotation that includes @EnableAutoConfiguration among others. It enables Spring Boot’s auto-configuration and component scanning.

By using @EnableAutoConfiguration, you can start building Spring Boot applications quickly, taking advantage of pre-configured settings for various common use cases. However, you can still override and customize these configurations as needed to tailor your application to specific requirements.


21. @SpringBootConfiguration

The @SpringBootConfiguration annotation is used in a Spring Boot application to declare a class as a configuration class. Configuration classes in Spring Boot are used to define beans and configure various components of the application. these annotations in Spring Boot are a specialization of the standard Spring @Configuration annotation, specifically tailored for Spring Boot applications.

Purpose: It is used to designate a class as a configuration class in a Spring Boot application. Configuration classes are responsible for defining and configuring beans, properties, and other components of the application.


@SpringBootApplication
public class MySpringBootApplication {

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

    @Bean
    public MyBean myBean() {
        return new MyBean();
    }
}

In this example

  • @SpringBootApplication is a meta-annotation that combines several annotations, including @SpringBootConfiguration. It marks the main application class and includes auto-configuration and component scanning features.
  • MyBean is a custom bean that is defined using the @Bean annotation within the MySpringBootApplication class.

By using @SpringBootConfiguration, you signal to Spring Boot that this class serves as a configuration source for your application. Spring Boot will then scan this class for bean definitions and other configuration settings.

In summary, @SpringBootConfiguration is a specialized version of the @Configuration annotation used in Spring Boot applications to designate a class as a configuration source for defining beans and configuring components in your Spring Boot application.


22. @Valid

In Spring Boot, the @Valid annotation is used to indicate that a method parameter should be validated. It is often used in combination with other annotations in Spring Boot like @RequestBody or @RequestParam to ensure that the incoming data is valid according to the specified validation rules. This annotation triggers validation based on the constraints defined in your domain objects using Bean Validation annotations in Spring Boot like @NotNull, @Size, @Email, etc.

First, you need to include the necessary dependencies in your project’s pom.xml file to enable validation. You typically need the spring-boot-starter-validation dependency for Spring Boot to support validation.

<dependencies>
    <!-- Other dependencies -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-validation</artifactId>
    </dependency>
</dependencies>

Create a simple domain class with validation annotations in Spring Boot. For example:

public class User {
    @NotBlank(message = "Name cannot be blank")
    private String name;

    @Email(message = "Email should be valid")
    private String email;

    // Getters and setters
}

In your Spring Boot controller, use the @Valid annotation along with @RequestBody to validate the incoming JSON data:


@RestController
@RequestMapping("/users")
@Validated
public class UserController {

    @PostMapping("/create")
    public ResponseEntity<String> createUser(@Valid @RequestBody User user) {
        // Process the valid user object
        // If the object is not valid, Spring will automatically handle validation errors.
        return ResponseEntity.ok("User created successfully");
    }
}

In the above example

  • We define a User class with validation annotations in spring boot like @NotBlank and @Email.
  • In the UserController, we use the @Valid annotation in conjunction with @RequestBody to validate the User object passed in the request body.
  • If the data in the request body doesn’t meet the validation constraints, Spring Boot will automatically handle the validation errors and return a response with error details.

Using @Valid along with Bean Validation annotations in Spring Boot helps ensure that your Spring Boot application receives valid data and provides meaningful error responses when validation fails.


23. @NotNull

In Spring Boot, the @NotNull annotation is used to indicate that a particular field or method parameter cannot be assigned a null value. It is commonly used for validation purposes to ensure that required data is present and not missing.

Use the @NotNull annotation to specify that a field or method parameter should not be null. You can apply this annotation to fields in your model classes or method parameters in your controller methods, for example:

public class User {
    @NotNull
    private String username;
    
    @NotNull
    private String password;
    
    // Getters and setters
}

In this example, the @NotNull annotation is used to ensure that the username and password fields in the User class are not assigned null values.

  • When you receive user input or data, such as in a controller method, you can use the @Valid annotation to trigger validation and check for @NotNull constraints. For instance:

In this example, the @Valid annotation is used on the user parameter of the createUser method. When a request is made to create a user, Spring Boot will automatically validate the User object against the @NotNull constraints defined in the User class. If any of the constraints are violated (e.g., username or password is null), Spring Boot will return a validation error response.

Using the @NotNull annotation in combination with Spring Boot’s validation framework helps ensure that required data is present and provides meaningful validation error messages when it’s not.


24. @NotEmpty

In Spring Boot, the @NotEmpty annotation is used to validate that a field or property of a Java class is not empty (i.e., it should not be null and should have a length greater than zero). These annotations in spring boot are typically used in conjunction with other validation annotations in spring boot to ensure that the data entered into a form or received as input meets certain criteria.

Example

Suppose you have a simple Spring Boot entity class called User:


@Entity
@Table(name = "users")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotEmpty(message = "Username cannot be empty")
    private String username;

    @NotEmpty(message = "Password cannot be empty")
    private String password;

    // Constructors, getters, and setters
}

In this example, we have used the @NotEmpty annotation to ensure that the username and password fields of the User class are not empty when validating user input. If a user tries to create or update a User instance with empty values for these fields, Spring Boot will throw a validation error with the specified error message.


25. @NotBlank

In Spring Boot, the @NotBlank annotation is part of the Java Bean Validation framework (JSR-380) and is used to specify that a field or method parameter must not be null and must contain at least one non-whitespace character. It is commonly used to validate that a String is not empty or consists solely of whitespace characters.

example

public class User {
    @NotBlank
    private String username;

    @NotBlank
    private String password;

    // getters and setters
}
  • Create a controller or service class that uses the User class and performs validation:
@RestController
@RequestMapping("/users")
@Validated
public class UserController {

    @PostMapping("/register")
    public ResponseEntity<String> registerUser(@Valid @RequestBody User user) {
        // Your registration logic here
        return ResponseEntity.ok("User registered successfully");
    }
}

In the above example

  • @Validated is used at the class level to enable validation for this controller.
  • @Valid is used on the User parameter of the registerUser method to indicate that Spring should validate the incoming User object.
  • The @NotBlank annotations in spring boot on the username and password fields of the User class enforce that these fields must not be empty or contain only whitespace when a user is registered.

When you send a POST request to /users/register with a JSON payload containing a User object that has empty or whitespace-only username or password, Spring Boot will automatically perform validation and return a validation error response if the input doesn’t meet the specified constraints.


26. @Size

In Spring Boot, the @Size annotation is used to specify the size constraints for a field or property of a JavaBean (a class that follows JavaBean conventions). This annotation can be particularly useful for validating the length of strings, collections, or arrays. It ensures that the annotated field’s value meets the specified size criteria.


public class MyBean {

    @Size(min = 2, max = 50, message = "Name must be between 2 and 50 characters")
    private String name;

    // getters and setters
}

In this example

  • We have a MyBean class with a name field annotated with @Size.
  • The min attribute specifies the minimum allowed length for the name field, which is 2 characters.
  • The max attribute specifies the maximum allowed length for the name field, which is 50 characters.
  • The message attribute provides a custom error message to be displayed if the size constraint is violated.

You can use the @Size annotation in conjunction with Spring’s validation framework to automatically validate input data in your Spring Boot application. For instance, in a controller method, you can use @Valid to trigger the validation and capture validation errors in a BindingResult object:


27.@ Min

In Spring Boot, the @Min annotation is used to specify the minimum value that a field or property in a Java bean should have. It is often used for validation purposes to ensure that the value entered or provided meets a minimum requirement. The @Min annotation is typically used in conjunction with other validation annotations in spring boot like @NotNull or @Valid to create robust validation rules for your application.

  • @Min is a Spring Boot validation annotation used to specify the minimum value allowed for a numeric field or property.
  • It ensures that the annotated field’s value is greater than or equal to the specified minimum value.

Example


public class Product {
    private Long id;

    @Min(value = 1, message = "Product price must be at least 1")
    private double price;

    // Constructors, getters, and setters
}

In this example, we have a Product class with a price field. We’ve applied the @Min annotation to the price field, specifying that the minimum allowed value is 1. If someone tries to create an Product object with a price less than 1, a validation error will occur, and you can handle this error in your Spring Boot application.


28. @RestControllerAdvice

The @RestControllerAdvice annotation in Spring Boot is used to define global exception handlers for your RESTful web services. It allows you to centralize exception-handling logic and apply it across multiple controller classes. This is particularly useful for handling exceptions consistently and returning standardized error responses in your Spring Boot application.

How it works

  • @RestControllerAdvice is usually placed on a class that is responsible for handling exceptions thrown by the controllers in your application.
  • It combines the functionality of @ControllerAdvice (for MVC controllers) and @ResponseBody (for RESTful controllers).
  • When an exception occurs in any controller method, Spring Boot will look for a matching @ExceptionHandler method in the @RestControllerAdvice class to handle that exception.
  • The annotated class can also include other methods for global behavior, like handling custom response headers, customizing error messages, and more.

Example

Let’s say you have a Spring Boot application with RESTful endpoints, and you want to handle a custom exception called CustomNotFoundException. You can define a @RestControllerAdvice class to handle this exception globally:

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(CustomNotFoundException.class)
    @ResponseBody
    public ResponseEntity<String> handleCustomNotFoundException(CustomNotFoundException ex) {
        // Create a custom error message and return it with a 404 status code
        String errorMessage = "Resource not found: " + ex.getMessage();
        return new ResponseEntity<>(errorMessage, HttpStatus.NOT_FOUND);
    }
}
  • In this example, GlobalExceptionHandler is a @RestControllerAdvice class that contains an @ExceptionHandler method for the CustomNotFoundException class. When this exception is thrown anywhere in your application, this method will be invoked, and it will return a custom error response with a 404 status code.

With @RestControllerAdvice, you can handle various exceptions and define consistent error responses across your entire Spring Boot application without duplicating code in individual controllers.


29. @ExceptionHandler

In Spring Boot, the @ExceptionHandler annotation is used to handle exceptions that occur during the processing of a request in a Spring MVC controller. It allows you to define methods that can handle specific exceptions and return custom responses to the client when those exceptions occur.

Example

Create a controller advice class and annotate it with @ControllerAdvice. This class will contain methods annotated @ExceptionHandler to handle exceptions globally for all controllers in your application.

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseEntity<String> handleException(Exception ex) {
        // Create a custom error message or response here
        String errorMessage = "An error occurred: " + ex.getMessage();
        return new ResponseEntity<>(errorMessage, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

the handleException method is annotated with @ExceptionHandler(Exception.class), which means it will handle any unhandled exception of type Exception. It returns a custom error message along with an HTTP status code of 500 (Internal Server Error).

In this example


30. @ResponseStatus

In Spring Boot, the @ResponseStatus annotation is used to specify the HTTP response status code that should be sent back to the client when a particular exception is thrown within a controller method. It allows you to customize the HTTP status code and, optionally, a reason phrase for different exception scenarios.

example

  • Create a custom exception class and annotate it @ResponseStatus to specify the desired HTTP status code.
@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
    public ResourceNotFoundException(String message) {
        super(message);
    }
}

In this example, we’ve created a custom exception called ResourceNotFoundException and annotated it with @ResponseStatus(HttpStatus.NOT_FOUND). This means that when this exception is thrown, the HTTP response status code will be set to 404 (Not Found).


31. @Custom Validation Annotations

In Spring Boot, you can create custom validation annotations in Spring Boot by combining the power of Spring’s @Constraint annotation and Java’s annotations. Custom validation annotations in Spring Boot allow you to define your own validation rules and apply them to fields or methods in your Spring components like DTOs, entities, or request objects


In Spring Boot, you can create custom validation annotations in Spring Boot by combining the power of Spring’s @Constraint annotation and Java’s annotations. Custom validation annotations in Spring boot allow you to define your own validation rules and apply them to fields or methods in your Spring components like DTOs, entities, or request objects. Here’s a short description of how to create custom validation annotations in Spring Boot with an example:

  • Create a Custom Validation Annotation: To create a custom validation annotation, you’ll first define the annotation itself. This annotation should be annotated with @Constraint and specify a validator class that implements the ConstraintValidator interface. For example:
@Target({ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = CustomValidator.class)
@Documented
public @interface CustomValidation {
    String message() default "Custom validation failed";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

Create a Custom Validator Class: Next, you need to create a validator class that implements the ConstraintValidator interface. This class will contain the logic to validate the annotated field or method. For example:

public class CustomValidator implements ConstraintValidator<CustomValidation, String> {

    @Override
    public void initialize(CustomValidation constraintAnnotation) {
        // Initialization, if needed
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        // Custom validation logic
        return value != null && value.startsWith("CustomPrefix");
    }
}

Using the Custom Annotation: You can now use your custom annotation in your Spring components. Here’s an example of applying the custom annotation to a field in a DTO class:

public class MyDto {
    @CustomValidation
    private String customField;

    // Getter and Setter methods
}

Utilizing Validation in Spring Components: To trigger validation in your Spring components (e.g., controller methods), you can use Spring’s @Valid annotation:

@RestController
@Validated
public class MyController {
    
    @PostMapping("/my-endpoint")
    public ResponseEntity<String> myEndpoint(@Valid @RequestBody MyDto myDto) {
        // Your controller logic here
    }
}

In this example, when a POST request is made to /my-endpoint, Spring Boot will automatically validate the MyDto object using the custom validation logic defined in the CustomValidator class.

Custom validation annotations in Spring Boot are a powerful way to encapsulate and reuse validation rules throughout your Spring Boot application, making your code more maintainable and clean.

Ram Chadar

Hello! I'm Ram Chadar, a passionate software developer and freelancer based in Pune. Welcome to my blog, where I share my experiences, insights, and knowledge in the world of software development, different technologies, freelancing, and more.

View all posts by Ram Chadar →

4 thoughts on “2. Advance annotations in spring boot – Tested

  1. Very nice post. I simply stumbled upon your blog and wished to say that I have truly enjoyed browsing your blog posts. In any case I’ll be subscribing for your rss feed and I hope you write once more very soon!

Leave a Reply

Your email address will not be published. Required fields are marked *