rspec/rules/S3305/java/rule.adoc
Fred Tingaud 16f6c0aecf
Inline adoc when include has no additional value (#1940)
Inline adoc files when they are included exactly once.

Also fix language tags because this inlining gives us better information
on what language the code is written in.
2023-05-25 14:18:12 +02:00

62 lines
1.7 KiB
Plaintext
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

== Why is this an issue?
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
[source,java]
----
@Configuration
public class FooConfiguration {
@Autowired private DataSource dataSource; // Noncompliant
@Bean
public MyService myService() {
return new MyService(this.dataSource);
}
}
----
=== Compliant solution
[source,java]
----
@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.
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Inject this field value directly into "xxx", the only method that uses it.
'''
== Comments And Links
(visible only on this page)
=== on 13 Jun 2018, 13:28:53 Andrei Epure wrote:
Are ``++@Autowired++`` setters and constructors on a ``++@Configuration++`` object out of scope of this rule?
endif::env-github,rspecator-view[]