Recipe Name:
Field injection is not recommended
Description:
Field injection is not recommended, because the list of required dependencies are unclear during instance creation. This makes testing more difficult and could lead to runtime exceptions when the bean is instantiated without spring.
Level:
info
Language:
  • java
  • kotlin
Tags:
  • Spring
  • Spring Core
  • dependency injection
  • framework specific
  • quality
Documentation

Field injection is not recommended, because the list of required dependencies are unclear during instance creation. This makes testing more difficult and could lead to runtime exceptions when the bean is instantiated without spring.

To clearly state the required dependencies of the class, they should be added to the constructor that has the @Autowired annotation. This way, these dependencies can be provided more easily through Spring's dependency injection mechanism.

Correct code example
@Configuration
public class Config {

    @Bean
    public Engine engine() {
        return new Engine("v8");
    }

    @Bean
    public Transmission transmission() {
        return new Transmission("sliding");
    }
}

@Component
public class Car {

    @Autowired
    public Car(Engine engine, Transmission transmission) {
        this.engine = engine;
        this.transmission = transmission;
    }
}
References
Recipe
id: scw:spring:field-injection
version: 10
metadata:
  name: Field injection is not recommended
  shortDescription: Field injection is not recommended, because the list of required dependencies are unclear during instance creation. This makes testing more difficult and could lead to runtime exceptions when the bean is instantiated without spring.
  level: info
  language: java; kotlin
  enabled: true
  comment: ""
  descriptionFile: descriptions/Field_injection_is_not_recommended.html
  excludeTestDirs: true
  tags: Spring;Spring Core;dependency injection;framework specific;quality
search:
  field:
    annotation:
      type: org.springframework.beans.factory.annotation.Autowired
scopes:
  not:
    library:
      name:
        contains: org.projectlombok:lombok
        caseSensitive: false
availableFixes: []