javaspringgradlepmd

PMD Ignore Spring Field Injections in gradle config


Currently I have several Controllers that inject dependencies through a field marked with @Autowired. When I try to run gradle build the following violations come up.

enter image description here

These all correspond to the instances of where a spring component has been injected.

I am aware of the ignoreAnnotations property that seems to exist for PMD, however, I am not sure if one can actually specify this in a gradle configuration?

Any help would be appreciated.


Solution

  • The root cause is: field injection is code smell and bad design practice.

    When @Autowired is used on a non-transient field it can cause issues with serialization. This is because the field will not be properly initialized when the object is deserialized, leading to a NullPointerException when the object is used.

    To fix this issue either make the fields transient or -- much better -- use constructor injection. To use constructor injection add a constructor to your class that takes all of the required dependencies as arguments, and annotate the constructor with @Autowired (the annotation is optional in modern Spring versions).

    @Component
    class MyClass {
        private final Dependency1 dependency1;
        private final Dependency2 dependency2;
    
        @Autowired
        public MyClass(Dependency1 dependency1, Dependency2 dependency2) {
            this.dependency1 = dependency1;
            this.dependency2 = dependency2;
        }
    }