Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

218
Vistas
Constructor Dependency Injection in Spring Framework

As far as I know constructors injection enforces mandatory dependencies and setters injection allow optional dependencies, but then...

Wouldn't be possible then this approach ???

@Component
public class Car {

    @Autowired(required=false)
    public Car(Engine engine, Transmission transmission) {
        this.engine = engine;
        this.transmission = transmission;
    }
}
about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Your approach won't work as Spring will not inject null if no bean of given type is found. If you set @Autowired(required=false) on the setter method, in case there is no such bean this setter won't be called. It is not possible with the constructor.

For Spring version 4.1+ you can use Java 8 Optional for declaring optional dependencies:

@Component
public class Car {

    @Autowired
    public Car(Engine engine, Optional<Transmission> transmission) {
        this.engine = engine;
        this.transmission = transmission.orElse(null);
    }
}

In this case Spring will understand that Engine is required and but Transmission is optional. So if no bean of type Transmission is found then Optional.empty() is injected.

about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda