Recipe Name:
Field injection is not recommended (lombok)
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
  • Lombok
  • 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: Field_injection_is_not_recommended_lombok
version: 10
metadata:
  name: Field injection is not recommended (lombok)
  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;Lombok;quality
search:
  field:
    annotation:
      type: org.springframework.beans.factory.annotation.Autowired
scopes:
  library:
    name:
      contains: org.projectlombok:lombok
      caseSensitive: false
availableFixes:
- name: use lombok to inject dependencies
  actions:
  - addAnnotation:
      annotation: '@lombok.RequiredArgsConstructor'
      target: parentClass
  - rewrite:
      to: private final {{{ typeElement }}} {{{ qualifier }}};