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.
@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.
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
.
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.");
}
}
@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;
}
}
Jorge García
Fullstack developer