Uploaded image for project: 'Rules Repository'
  1. Rules Repository
  2. RSPEC-4288

Spring components should use constructor injection

    Details

    • Type: Code Smell Detection
    • Status: Active
    • Resolution: Unresolved
    • Labels:
    • Message:
      Remove this annotation and use constructor injection instead.
    • Highlighting:
      Hide

      Primary:

      • Annotation of injected field
        Secondary (if possible):
      • on all the other fields with injection annotation
      • finally, on constructor (if present)
      Show
      Primary: Annotation of injected field Secondary (if possible): on all the other fields with injection annotation finally, on constructor (if present)
    • Default Severity:
      Major
    • Impact:
      Low
    • Likelihood:
      High
    • Covered Languages:
      Java
    • Remediation Function:
      Linear
    • Linear Argument Description:
      2min by injected field
    • Linear Factor:
      2min
    • Analysis Scope:
      Main Sources

      Description

      Spring @Controller, @Service, and @Repository classes are singletons by default, meaning only one instance of the class is ever instantiated in the application. Typically such a class might have a few static members, such as a logger, but all non-static members should be managed by Spring and supplied via constructor injection rather than by field injection.

      This rule raise an issue when any non-static member of a Spring component has an injection annotation, or if the constructor of Spring component does not have injection annotation.

      Noncompliant Code Example

      @Controller
      public class HelloWorld {
       
        @Autowired
        private String name = null; // Noncompliant
      
        HelloWorld() {
         // ...
        }
      
        // ...
      }
      

      Compliant Solution

      @Controller
      public class HelloWorld {
       
        private String name = null;
      
        @Autowired
        HelloWorld(String name) {
          this.name = name;
         // ...
        }
      
        // ...
      }
      

        Attachments

          Issue Links

            Activity

              People

              • Assignee:
                Unassigned
                Reporter:
                michael.gumowski Michael Gumowski
              • Votes:
                0 Vote for this issue
                Watchers:
                2 Start watching this issue

                Dates

                • Created:
                  Updated: