Skip to content
← blog/

Spring Annotations

4 min read #springboot #spring

Spring uses an Inversion of control architecture and spring container or ioc container is used to inject objects. Spring container basically manages the Beans and Inject into the program whenever we want. A key aspect of Spring is its configuration, which allows developers to define and configure various components and services within the application.

Annotations in Java are metadata tags that provide additional information about code elements, such as classes, methods, fields, and parameters. Spring annotations are used within the Spring context to enhance the functionality of Spring beans and components. They are processed at runtime by Spring’s IoC container.

Let’s understand some common spring annotations

1. @Bean Annotation

As in xml based configuration, we used to write bean tags to define custom beans @Bean is used for the same purpose i.e. to define custom beans. By using @Bean in a configuration class, you explicitly tell Spring to create and manage a bean based on the method’s return value. This is particularly useful when you need to configure or customize the bean instance before it is added to the Spring application context.

class Car{
      start(){
             System.out.println("started");
         }
  }
@Configuration
class AppConfig{
      @Bean
       public Car car(){
             return new Car();
       }
}

Here @Configuration annotation used to mark AppConfig class as configuration class. Configuration classes play a vital role in Spring applications as they define how the application’s beans are created, configured, and wired together. They serve as an alternative to XML-based configuration, allowing developers to configure Spring beans using pure Java code.

By default, the bean name will be the same as the method name. To customize the bean name, use its’ name‘ or ‘value‘ attribute.

@Configuration
public class AppConfig {

    @Bean(name = "customBeanName") // Specify the desired bean name here
    public MyCarService myCarService() {
        return new MyCarServiceImpl();
    }
}

2. @Component

@Component This annotation marks a Java class as a Spring bean, allowing the Spring container to manage it. You can use @ComponentScan to specify packages for component scanning.

@Component
public class Car{
///.....
}

3.@Service ,@Repository and @Controller

These are specialized types of @Component annotations. They are used to distinguish between different type of beans.

@Service annotation is used for service layer. It indicates that the class plays a service role and is typically used in the service layer of the application. Service classes that contain business logic, perform data processing or interact with multiple repositories.

@Repository indicates that the class is a data repository, often for storing and retrieving data from a database. spring provides additional benefits for classes annotated with @Repository, such as exception translation (converting database-specific exceptions to Spring’s DataAccessException hierarchy) and automatic transaction management.

@Controller used in spring mvc aapplication used to handle incoming http requests. It indicates that the class is a controller responsible for processing and responding to HTTP requests.

3.@Autowired

@Autowired is the spring annotation that is used for automatic dependency injection. The @Autowired annotation can be applied to fields, methods, or constructors of a class to indicate that Spring should automatically wire the required dependency. When a bean with a certain type is needed, Spring searches the application context for a suitable candidate and injects it into the annotated field, method, or constructor.

//constructor injection using @Autowired
@Component
public class Bike {
    private Motercycle motercycle;

    @Autowired
    public Bike(Motercycle motercycle) {
        this.motercycle = motercycle;
    }

 }

//setter injection
@Component
public class Bike {
    private Motercycle motercycle;

    @Autowired
    public setMotercycle(Motercycle motercycle) {
        this.motercycle = motercycle;
    }

 }

//field injection
@Component
public class Bike {
    @Autowired
    private Motercycle motercycle;

 }

4.@Qualifier

When using @Autowired spring will search for a bean that matches the type that needs to be injected. If there are multiple beans of the same type are available, you can use the @Qualifier annotation to specify which bean should be injected.

@Service
public class CarService {
    private final PaymentService paymentService;

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

}

In this example, the creditCardPayment bean is injected into the OrderService using the @Qualifier annotation.

5.@PostConstruct and @PreDestroy

  • @PostConstruct: This annotation is used on a method that should be executed after a bean is initialized.
  • @PreDestroy: This annotation is used on a method that should be executed before a bean is destroyed.

There are more annotations @Value , @RequestMapping , @PathVariable, @RequestParam you can learn more about it in the spring official documentation.

Spring annotations have changed the way developers work with the Spring Framework. They promote cleaner, more concise code by reducing the need for XML configuration and enabling powerful features like dependency injection and aspect-oriented programming.

Checkout my previous articles

inversion of control and dependency injection

Jar and Fat Jar

I hope you understood the these spring annotations. follow me for more engaging software engineering content!

Happy Coding🚀🚀