The @Autowired annotation in Spring, and the standard JSR-330 @Inject annotation (from jakarta.inject or
javax.inject) that Spring also supports, are used for automatic dependency injection. They allow Spring to resolve and inject the
required beans into your bean. For example, to inject a @Repository object into a @Service.
The Spring dependency injection mechanism cannot identify which constructor to use for auto-wiring when multiple constructors are present in a class. This ambiguity can cause the application to crash at runtime, and it makes the code less clear to understand and more complex to extend and maintain.
Use the @Autowired or @Inject annotation to specify which constructor to use for dependency injection.
@Component
public class ExampleClass { // Noncompliant: multiple constructors present and no @Autowired or @Inject annotation to specify which one to use
private final DependencyClass1 dependency1;
public ExampleClass() {
throw new UnsupportedOperationException("Not supported yet.");
}
public ExampleClass(DependencyClass1 dependency1) {
this.dependency1 = dependency1;
}
// ...
}
@Component
public class ExampleClass {
private final DependencyClass1 dependency1;
public ExampleClass() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Autowired // or @Inject from jakarta.inject or javax.inject
public ExampleClass(DependencyClass1 dependency1) {
this.dependency1 = dependency1;
}
// ...
}