== Why is this an issue?

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.

=== Noncompliant code example

[source,java]
----
@Controller
public class HelloWorld {

  @Autowired
  private String name = null; // Noncompliant

}
----

=== Compliant solution

As of Spring 4.3
[source,java]
----
@Controller
public class HelloWorld {

  private String name = null;

  HelloWorld(String name) {
    this.name = name;
  }
}
----

Before Spring 4.3
[source,java]
----
@Controller
public class HelloWorld {

  private String name = null;

  @Autowired
  HelloWorld(String name) {
    this.name = name;
  }
}
----

ifdef::env-github,rspecator-view[]

'''
== Implementation Specification
(visible only on this page)

=== Message

Remove this annotation and use constructor injection instead.


=== Highlighting

Primary: 

* Annotation of injected field

Secondary (if possible):

* on all the other fields with injection annotation
** message: 'Remove also this annotation.'
* finally, on constructor (if present)
** message: 'Constructor where you can inject these fields.'


'''
== Comments And Links
(visible only on this page)

=== on 8 Oct 2018, 14:16:58 Thomas Turrell-Croft wrote:
Spring 4.3 does not required the autowired annotation if there is only one constructor.  See the https://spring.io/blog/2016/03/04/core-container-refinements-in-spring-framework-4-3#implicit-constructor-injection-for-single-constructor-scenarios[blog post] announcing 4.3 for more details.


I would suggest that the compliant solution should look more like:


----
@Controller
public class HelloWorld {

  private final String name;

  public HelloWorld(String name) {
    this.name = name;
   // ...
  }

  // ...
} 
----

I believe that the dependancies should be `final`.

endif::env-github,rspecator-view[]
