Dependency injection Spring Boot

Viewed 48

Can I use two kinds of dependency injection in the same class?

i.e.

public class Test {
    
    private ObjectTwo o2;

    @Autowired                     // constructor injection
    public Test(ObjectTwo o2 ) {
      this.o2=o2;
    }

    @Autowired                     // field injection
    private ObjectOne o1;

    ...

    "using o1"
    "using o2"

    ...
}

Related Question

https://stackoverflow.com/a/70656587/17755094

1 Answers

Yes you can. You can inject o1 and o2 and differentiate them using the @Qualifier annotation along with @Autowired. Refer here - https://www.baeldung.com/spring-qualifier-annotation.

Here's an example; you could have as many "Formatter" instances as you want as long as you use the @Qualifier annotation on them to differentiate which you want to inject.

@Component("fooFormatter")
public class FooFormatter implements Formatter {
 
    public String format() {
        return "foo";
    }
}

@Component("barFormatter")
public class BarFormatter implements Formatter {
 
    public String format() {
        return "bar";
    }
}

public class FooService {
    @Autowired
    @Qualifier("fooFormatter")
    private Formatter formatter;
}

Mixing Injection Types

You can mix constructor and property injection (setters), so I'm sure you can also mix annotation and constructor injection.

Related