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

Factory method injection should be used in "@Configuration" classes

    XMLWordPrintable

    Details

    • Type: Code Smell Detection
    • Status: Active
    • Resolution: Unresolved
    • Message:
      Inject this field value directly into "xxx", the only method that uses it.
    • Default Severity:
      Critical
    • Impact:
      High
    • Likelihood:
      Low
    • Default Quality Profiles:
      Sonar way
    • Covered Languages:
      Java
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      5min
    • Analysis Scope:
      Main Sources

      Description

      When @Autowired is used, dependencies need to be resolved when the class is instantiated, which may cause early initialization of beans or lead the context to look in places it shouldn't to find the bean. To avoid this tricky issue and optimize the way the context loads, dependencies should be requested as late as possible. That means using parameter injection instead of field injection for dependencies that are only used in a single @Bean method.

      Noncompliant Code Example

      @Configuration
      public class ​FooConfiguration {
      
        @Autowired private ​DataSource dataSource​;  // Noncompliant
      
        @Bean
        public ​MyService myService() {
          return new ​MyService(this​.dataSource​);
        }
      }
      

      Compliant Solution

      @Configuration
      public class ​FooConfiguration {
       
       @Bean
        public ​MyService myService(DataSource dataSource) {
          return new ​MyService(dataSource);
        }
      }
      

      Exceptions

      Fields used in methods that are called directly by other methods in the application (as opposed to being invoked automatically by the Spring framework) are ignored by this rule so that direct callers don't have to provide the dependencies themselves.

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              ann.campbell.2 Ann Campbell
              Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

                Dates

                Created:
                Updated: