Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

219
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!