Volver a la página principal
lunes 10 febrero 2025
14

Cómo utilizar @Primary en Spring Boot

La anotación @Primary en Spring Boot se usa para indicar qué bean debe ser el predeterminado cuando existen múltiples implementaciones de una misma interfaz. Esto ayuda a evitar errores de ambigüedad al realizar la inyección de dependencias.

¿Qué es @Primary en Spring Boot?

Cuando hay varias implementaciones de un mismo tipo en el contexto de Spring, el framework no sabe cuál usar de manera predeterminada. @Primary resuelve este problema marcando un bean como la opción principal. Si no se usa @Primary, Spring requiere el uso de @Qualifier para especificar qué implementación inyectar.

Ejemplo de uso

import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

public interface NotificacionService {
    void enviarMensaje(String mensaje);
}

@Service
@Primary
class EmailNotificacionService implements NotificacionService {
    @Override
    public void enviarMensaje(String mensaje) {
        System.out.println("Enviando email: " + mensaje);
    }
}

@Service
class SmsNotificacionService implements NotificacionService {
    @Override
    public void enviarMensaje(String mensaje) {
        System.out.println("Enviando SMS: " + mensaje);
    }
}

En este caso, si se inyecta NotificacionService sin especificar un @Qualifier, Spring usará EmailNotificacionService porque está marcado con @Primary.

Inyección del servicio

import org.springframework.stereotype.Component;

@Component
public class NotificacionController {
    private final NotificacionService notificacionService;

    public NotificacionController(NotificacionService notificacionService) {
        this.notificacionService = notificacionService;
    }

    public void enviar() {
        notificacionService.enviarMensaje("Hola, este es un mensaje.");
    }
}

Alternativa: Uso de @Qualifier

Si se desea utilizar una implementación específica en lugar de la marcada con @Primary, se puede usar @Qualifier:

@Component
public class NotificacionController {
    private final NotificacionService notificacionService;

    public NotificacionController(@Qualifier("smsNotificacionService") NotificacionService notificacionService) {
        this.notificacionService = notificacionService;
    }
}
Compartir:
Creado por:
Author photo

Jorge García

Fullstack developer