Mastering Spring Annotations: The Ultimate Guide for Beginners


@Component Annotation in Spring

The @Component annotation marks a class as a Spring-managed bean.
It is a stereotype annotation, meaning it indicates that the class is a candidate for auto-detection during component scanning.

If a class is not annotated with @Component (or other stereotype annotations like @Service, @Repository, or @Controller), Spring will not register it in the application context.

Functionality

  1. Bean Registration

When a class is annotated with @Component and component scanning is enabled, Spring automatically registers the bean in the application context.

  1. Dependency Injection

Spring can automatically inject the bean into other components where it is required, using @Autowired or constructor injection.

Example:

import org.springframework.stereotype.Component;

@Component
public class ComponentClass {
    // Class implementation here
}
Enter fullscreen mode

Exit fullscreen mode

@bean Annotation in Spring

The @bean annotation is a method-level annotation used to explicitly define a Spring bean.
It is typically used when you want to create a third-party or custom object that cannot be annotated directly with @Component.

A method annotated with @bean inside a class annotated with @Configuration tells Spring that the return value of this method should be registered as a bean in the application context.

Example:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {

    @Bean
    public SomeApiClientFromALibrary someClassFromLibrary() {
        return new SomeApiClientFromALibrary();
    }
}
Enter fullscreen mode

Exit fullscreen mode

@Configuration Annotation

The @Configuration annotation indicates that a class contains Spring bean definitions.
If a class is annotated with @Configuration, the methods inside it that are annotated with @bean will produce beans managed by the IoC container.

It replaces the old XML-based configuration and provides a type-safe, Java-based configuration approach.

Example:

@Configuration
public class TestConfig {

    @Bean
    public Insert tester() {
        return new Insertion();
    }
}
Enter fullscreen mode

Exit fullscreen mode

@ComponentScan Annotation

The @ComponentScan annotation enables component scanning in Spring.
When enabled, Spring automatically detects and registers all the stereotype annotations —
@Controller, @Service, @Component, @Repository, and @Configuration — into the Spring IoC container, making them available for dependency injection.

@PostConstruct Annotation

The @PostConstruct annotation marks a method to be executed after the bean is initialized by Spring.
It is typically used to load or initialize data from an external source after bean creation.

The method must be non-static.

Only one @PostConstruct method is allowed per class.

It can have any access level (public, private, etc.).

Example:

import jakarta.annotation.PostConstruct;
import org.springframework.stereotype.Component;

@Component
public class PostExample {

    @PostConstruct
    public void postMethod() {
        System.out.println("PostConstruct method executed after bean initialization");
    }
}


Enter fullscreen mode

Exit fullscreen mode

@PreDestroy Annotation

The @PreDestroy annotation marks a method to be executed before the bean is destroyed.
It is useful for performing cleanup operations, such as closing connections, clearing caches, or stopping background threads.

Example:

import jakarta.annotation.PreDestroy;
import org.springframework.stereotype.Component;

@Component
public class PreDestroyExample {

    @PreDestroy
    public void destruct() {
        System.out.println("PreDestroy method executed before bean destruction");
    }
}
Enter fullscreen mode

Exit fullscreen mode

@primary Annotation

The @primary annotation is used when multiple beans of the same type exist in the Spring context.
It tells Spring which bean should be given preference during autowiring.

If a bean is annotated with @primary, that bean will be injected by default when there are multiple candidates.

Example:

public interface Message {
    String message();
}

@Component
public class WhatsApp implements Message {
    @Override
    public String message() {
        return "Hi from WhatsApp";
    }
}

@Component
@Primary
public class Telegram implements Message {
    @Override
    public String message() {
        return "Hello from Telegram";
    }
}

@Component
public class MessageService {

    @Autowired
    private Message msg;

    public String sendMessage() {
        return msg.message();
    }
}
Enter fullscreen mode

Exit fullscreen mode

➡ Here, Telegram will be injected because it is marked as @primary.

@Qualifier Annotation

The @Qualifier annotation is used when multiple beans of the same type exist and you want to specify exactly which bean should be injected.

It works alongside @Autowired to disambiguate bean selection.

Example:

public interface Message {
    String message();
}

@Component("whatsapp")
public class WhatsApp implements Message {
    @Override
    public String message() {
        return "Hi from WhatsApp";
    }
}

@Component("telegram")
public class Telegram implements Message {
    @Override
    public String message() {
        return "Hello from Telegram";
    }
}

@Component
public class MessageService {

    @Autowired
    @Qualifier("telegram")
    private Message telegramMessage;

    @Autowired
    @Qualifier("whatsapp")
    private Message whatsappMessage;

    public void displayMessages() {
        System.out.println(telegramMessage.message());
        System.out.println(whatsappMessage.message());
    }
}

Enter fullscreen mode

Exit fullscreen mode

➡ Here, @Qualifier(“telegram”) ensures the Telegram bean is injected.



Source link

Leave a Reply

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