rspec/rules/S3306/java/rule.adoc

67 lines
1.8 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +02:00
Field injection seems like a tidy way to get your classes what they need to do their jobs, but it's really a ``++NullPointerException++`` waiting to happen unless all your class constructors are ``++private++``. That's because any class instances that are constructed by callers, rather than instantiated by a Dependency Injection framework compliant with the JSR-330 (Spring, Guice, ...), won't have the ability to perform the field injection.
Instead ``++@Inject++`` should be moved to the constructor and the fields required as constructor parameters.
This rule raises an issue when classes with non-``++private++`` constructors (including the default constructor) use field injection.
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
class MyComponent { // Anyone can call the default constructor
@Inject MyCollaborator collaborator; // Noncompliant
public void myBusinessMethod() {
collaborator.doSomething(); // this will fail in classes new-ed by a caller
}
}
----
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
class MyComponent {
private final MyCollaborator collaborator;
@Inject
public MyComponent(MyCollaborator collaborator) {
Assert.notNull(collaborator, "MyCollaborator must not be null!");
this.collaborator = collaborator;
}
public void myBusinessMethod() {
collaborator.doSomething();
}
}
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Use constructor injection for this field.
'''
== Comments And Links
(visible only on this page)
=== on 14 Oct 2016, 13:31:17 Freddy Mallet wrote:
As decided with the Java team, let's remove this rule from the default "Sonar way" quality profile. See SONARJAVA-1880.
endif::env-github,rspecator-view[]