Spring Boot @Primary Example

1. Introduction

Spring Boot provides the @Primary annotation to give higher preference to a bean when multiple candidates are qualified to autowire a single-valued dependency. This helps in determining which bean should be given priority when multiple beans are present of the same type.

Key Points:

1. @Primary indicates that a bean should be given preference when multiple candidates are present for a single autowiring scenario.

2. It is used to avoid ambiguity by marking one bean as the primary autowire candidate.

3. @Primary can be used alongside @Component, @Service, @Repository, or @Controller annotations.

2. Implementation Steps

1. Define an interface with a method that will be implemented by multiple beans.

2. Create at least two implementations of this interface.

3. Annotate one of the implementations with @Primary to indicate it should be the default bean for autowiring.

4. Autowire the interface in a component without using @Qualifier to rely on the @Primary bean.

5. Implement the CommandLineRunner in the main application class to test the autowiring.

3. Implementation Example

Here is the complete code that demonstrates the usage of @Primary annotation:
// Step 1: Define a service interface
public interface CommunicationService {
    String communicate();
}

// Step 2: Create the first bean implementation
@Service
public class EmailService implements CommunicationService {
    public String communicate() {
        return "Communicating via Email";
    }
}

// Step 2: Create the second bean implementation and annotate it with @Primary
@Service
@Primary
public class SmsService implements CommunicationService {
    public String communicate() {
        return "Communicating via SMS";
    }
}

// Step 4: Autowire the CommunicationService interface in a component
@Component
public class NotificationManager {

    private final CommunicationService communicationService;

    @Autowired
    public NotificationManager(CommunicationService communicationService) {
        this.communicationService = communicationService;
    }

    public String sendNotification() {
        return communicationService.communicate();
    }
}

// Step 5: Create the main application class
@SpringBootApplication
public class PrimaryAnnotationExampleApplication implements CommandLineRunner {

    @Autowired
    private NotificationManager notificationManager;

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

    @Override
    public void run(String... args) {
        System.out.println(notificationManager.sendNotification());
    }
}

Output:

Communicating via SMS

Explanation:

1. CommunicationService is a simple interface with a method communicate.


Comments