Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
package checks.spring;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;

@Configuration
final class BasicFinalConfig { // Noncompliant {{Remove the "final" modifier from this "@Configuration" class.}}

@Bean
public String dataSource() {
return "dataSource";
}
}

@Configuration
final class FinalConfigMultipleBeans { // Noncompliant

@Bean
public String foo() {
return "foo";
}

@Bean
public String bar() {
return foo();
}
}

@Configuration
@EnableScheduling
final class FinalConfigOtherAnnotations { // Noncompliant

@Bean
public String scheduler() {
return "scheduler";
}
}

class OuterClass {
@Configuration
public static final class NestedFinalConfig { // Noncompliant

@Bean
public String taskScheduler() {
return "taskScheduler";
}
}
}

@Configuration(proxyBeanMethods = true)
final class FinalConfigProxyEnabled { // Noncompliant

@Bean
public String dataSource() {
return "dataSource";
}
}

@Configuration
class NonFinalConfig {

@Bean
public String dataSource() {
return "dataSource";
}

@Bean
public String jdbcTemplate() {
return dataSource();
}
}

@Configuration(proxyBeanMethods = false)
final class FinalConfigProxyDisabled {

@Bean
public String dataSource() {
return "dataSource";
}
}

@Component
final class FinalComponentNotConfiguration {

public String createDataSource() {
return "dataSource";
}
}

@Configuration
abstract class AbstractConfig {

@Bean
public String dataSource() {
return "dataSource";
}
}

class NoAnnotation {
public final class NotAConfigurationClass {
public String method() {
return "value";
}
}
}

class OuterClassCompliant {
@Configuration
public static class NestedNonFinalConfig {

@Bean
public String taskScheduler() {
return "taskScheduler";
}
}
}

// Meta-annotations like @SpringBootApplication are intentionally not detected by this rule
// to avoid complexity with determining proxyBeanMethods for composed annotations
@SpringBootApplication
final class FinalSpringBootApplication { // Compliant - meta-annotations not detected

@Bean
public String appBean() {
return "appBean";
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
/*
* SonarQube Java
* Copyright (C) SonarSource Sàrl
* mailto:info AT sonarsource DOT com
*
* You can redistribute and/or modify this program under the terms of
* the Sonar Source-Available License Version 1, as published by SonarSource Sàrl.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the Sonar Source-Available License for more details.
*
* You should have received a copy of the Sonar Source-Available License
* along with this program; if not, see https://sonarsource.com/license/ssal/
*/
package org.sonar.java.checks.spring;

import java.util.List;
import java.util.Optional;
import org.sonar.check.Rule;
import org.sonar.java.checks.helpers.ExpressionsHelper;
import org.sonar.java.checks.helpers.SpringUtils;
import org.sonar.java.model.ModifiersUtils;
import org.sonar.plugins.java.api.IssuableSubscriptionVisitor;
import org.sonar.plugins.java.api.tree.AnnotationTree;
import org.sonar.plugins.java.api.tree.AssignmentExpressionTree;
import org.sonar.plugins.java.api.tree.ClassTree;
import org.sonar.plugins.java.api.tree.IdentifierTree;
import org.sonar.plugins.java.api.tree.Modifier;
import org.sonar.plugins.java.api.tree.ModifierKeywordTree;
import org.sonar.plugins.java.api.tree.Tree;

@Rule(key = "S9021")
public class ConfigurationClassShouldNotBeFinalCheck extends IssuableSubscriptionVisitor {

@Override
public List<Tree.Kind> nodesToVisit() {
return List.of(Tree.Kind.CLASS);
}

@Override
public void visitNode(Tree tree) {
ClassTree classTree = (ClassTree) tree;

// Note: This check only detects direct @Configuration annotations, not meta-annotations
// like @SpringBootApplication. This is intentional to avoid complexity with proxyBeanMethods.
Optional<AnnotationTree> configurationAnnotation = getConfigurationAnnotation(classTree);
if (configurationAnnotation.isEmpty()) {
return;
}

Optional<ModifierKeywordTree> finalModifier = getFinalModifier(classTree);
if (finalModifier.isEmpty()) {
return;
}

if (hasProxyBeanMethodsDisabled(configurationAnnotation.get())) {
return;
}

reportIssue(finalModifier.get(), "Remove the \"final\" modifier from this \"@Configuration\" class.");
}

private static Optional<AnnotationTree> getConfigurationAnnotation(ClassTree tree) {
return tree.modifiers().annotations().stream()
.filter(annotation -> annotation.symbolType().is(SpringUtils.CONFIGURATION_ANNOTATION))
.findFirst();
}
Comment thread
gitar-bot[bot] marked this conversation as resolved.

private static Optional<ModifierKeywordTree> getFinalModifier(ClassTree tree) {
return ModifiersUtils.findModifier(tree.modifiers(), Modifier.FINAL);
}

private static boolean hasProxyBeanMethodsDisabled(AnnotationTree annotation) {
return annotation.arguments().stream()
.filter(argument -> argument.is(Tree.Kind.ASSIGNMENT))
.map(AssignmentExpressionTree.class::cast)
.anyMatch(ConfigurationClassShouldNotBeFinalCheck::setsProxyBeanMethodsToFalse);
}

private static boolean setsProxyBeanMethodsToFalse(AssignmentExpressionTree assignment) {
return "proxyBeanMethods".equals(((IdentifierTree) assignment.variable()).name()) &&
Boolean.FALSE.equals(ExpressionsHelper.getConstantValueAsBoolean(assignment.expression()).value());
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/*
* SonarQube Java
* Copyright (C) SonarSource Sàrl
* mailto:info AT sonarsource DOT com
*
* You can redistribute and/or modify this program under the terms of
* the Sonar Source-Available License Version 1, as published by SonarSource Sàrl.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the Sonar Source-Available License for more details.
*
* You should have received a copy of the Sonar Source-Available License
* along with this program; if not, see https://sonarsource.com/license/ssal/
*/
package org.sonar.java.checks.spring;

import org.junit.jupiter.api.Test;
import org.sonar.java.checks.verifier.CheckVerifier;

import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath;

class ConfigurationClassShouldNotBeFinalCheckTest {

@Test
void test() {
CheckVerifier.newVerifier()
.onFile(mainCodeSourcesPath("checks/spring/ConfigurationClassShouldNotBeFinalCheckSample.java"))
.withCheck(new ConfigurationClassShouldNotBeFinalCheck())
.verifyIssues();
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
<h2>Why is this an issue?</h2>
<p>Spring Framework uses CGLIB proxies to enforce singleton semantics for beans defined in <code>@Configuration</code> classes. When you call a
<code>@Bean</code> method from within another <code>@Bean</code> method, Spring intercepts the call through a proxy to return the singleton instance
rather than creating a new object.</p>
<p>The Java <code>final</code> keyword prevents class inheritance, which blocks CGLIB from creating the necessary subclass proxy. Without this proxy,
inter-bean method calls create new instances instead of retrieving the singleton, breaking Spring's container management.</p>
<p>This typically manifests as a <code>ConfigurationClassPostProcessor</code> exception during application startup, preventing the Spring context from
initializing.</p>
<h2>What is the potential impact?</h2>
<p>When Spring <code>@Configuration</code> classes are marked <code>final</code>, the application fails to start. The
<code>ConfigurationClassPostProcessor</code> throws an exception because CGLIB cannot create the required proxy subclass.</p>
<p>If this check were bypassed, the impact would be more subtle: inter-bean method calls would create duplicate instances instead of using singletons,
leading to:</p>
<ul>
<li><strong>Resource leaks</strong>: Multiple database connection pools or file handles</li>
<li><strong>Inconsistent state</strong>: Different parts of the application working with different object instances</li>
<li><strong>Configuration drift</strong>: Bean initialization logic executing multiple times with potentially different results</li>
</ul>
<h2>How to fix it</h2>
<p>Remove the <code>final</code> modifier from the <code>@Configuration</code> class. This allows Spring to create the CGLIB proxy needed to enforce
singleton semantics for inter-bean method calls.</p>
<h3>Code examples</h3>
<h4>Noncompliant code example</h4>
<pre data-diff-id="1" data-diff-type="noncompliant">
@Configuration
public final class DatabaseConfig { // Noncompliant

@Bean
public DataSource dataSource() {
return new HikariDataSource();
}

@Bean
public JdbcTemplate jdbcTemplate() {
return new JdbcTemplate(dataSource()); // May create duplicate DataSource
}
}
</pre>
<h4>Compliant solution</h4>
<pre data-diff-id="1" data-diff-type="compliant">
@Configuration
public class DatabaseConfig {

@Bean
public DataSource dataSource() {
return new HikariDataSource();
}

@Bean
public JdbcTemplate jdbcTemplate() {
return new JdbcTemplate(dataSource()); // Uses singleton DataSource
}
}
</pre>
<p>If you don't need inter-bean method calls and want to optimize startup performance, use <code>@Configuration(proxyBeanMethods = false)</code>. This
disables CGLIB proxying, allowing the class to be <code>final</code>. However, you must use dependency injection instead of calling <code>@Bean</code>
methods directly.</p>
<h4>Noncompliant code example</h4>
<pre data-diff-id="2" data-diff-type="noncompliant">
@Configuration
public final class DatabaseConfig { // Noncompliant

@Bean
public DataSource dataSource() {
return new HikariDataSource();
}

@Bean
public JdbcTemplate jdbcTemplate() {
return new JdbcTemplate(dataSource()); // Direct method call
}
}
</pre>
<h4>Compliant solution</h4>
<pre data-diff-id="2" data-diff-type="compliant">
@Configuration(proxyBeanMethods = false)
public final class DatabaseConfig {

@Bean
public DataSource dataSource() {
return new HikariDataSource();
}

@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) { // Injected parameter
return new JdbcTemplate(dataSource);
}
}
</pre>
<h2>Resources</h2>
<h3>Documentation</h3>
<ul>
<li><a href="https://docs.spring.io/spring-framework/reference/core/beans/java/configuration-annotation.html">Spring Framework - @Configuration
Annotation</a></li>
<li><a href="https://docs.spring.io/spring-framework/reference/core/aop/proxying.html">Spring Framework - Proxying Mechanisms</a></li>
<li><a href="https://docs.spring.io/spring-boot/reference/using/configuration-classes.html">Spring Boot - Configuration Classes</a></li>
</ul>
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"title": "\"@Configuration\" classes should not be final",
"type": "BUG",
"status": "ready",
"remediation": {
"func": "Constant/Issue",
"constantCost": "5min"
},
"tags": [
"spring"
],
"defaultSeverity": "Critical",
"ruleSpecification": "RSPEC-9021",
"sqKey": "S9021",
"scope": "Main",
"code": {
"impacts": {
"RELIABILITY": "HIGH"
},
"attribute": "LOGICAL"
}
}
Loading