Skip to content

Commit

Permalink
SONARJAVA-4685 Remove FP on invocation of non-bean methods (#4610)
Browse files Browse the repository at this point in the history
  • Loading branch information
dorian-burihabwa-sonarsource authored Dec 11, 2023
1 parent 2d20bd1 commit 97258b1
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,18 @@ public CompositeBean compositeBean() {
}
}

@Configuration(proxyBeanMethods = false)
static class InvokeNonBeanMethod {
public SimpleBean simpleBean() {
return new SimpleBean();
}

@Bean
public CompositeBean compositeBean() {
return new CompositeBean(simpleBean()); // Compliant, call to a method that is not a bean
}
}


static class SimpleBean {
// ...
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@

@Rule(key = "S6838")
public class DirectBeanMethodInvocationWithoutProxyCheck extends IssuableSubscriptionVisitor {
private static final String BEAN_ANNOTATION = "org.springframework.context.annotation.Bean";
private static final String CONFIGURATION_ANNOTATION = "org.springframework.context.annotation.Configuration";
private static final String SCOPE_ANNOTATION = "org.springframework.context.annotation.Scope";

Expand All @@ -59,7 +60,7 @@ public void visitNode(Tree tree) {

private static Optional<AnnotationTree> getConfigurationAnnotation(ClassTree tree) {
return tree.modifiers().annotations().stream()
.filter(annotationInstance -> annotationInstance.symbolType().is(CONFIGURATION_ANNOTATION))
.filter(annotation -> annotation.symbolType().is(CONFIGURATION_ANNOTATION))
.findFirst();
}

Expand Down Expand Up @@ -88,7 +89,7 @@ public NonProxiedMethodInvocationVisitor(ClassTree parentClass) {
public void visitMethodInvocation(MethodInvocationTree tree) {
super.visitMethodInvocation(tree);
MethodTree declaration = tree.methodSymbol().declaration();
if (declaration == null || hasPrototypeScope(declaration)) {
if (declaration == null || !isBeanMethod(declaration) || hasPrototypeScope(declaration)) {
return;
}
Tree parent = declaration.parent();
Expand All @@ -97,6 +98,11 @@ public void visitMethodInvocation(MethodInvocationTree tree) {
}
}

private static boolean isBeanMethod(MethodTree tree) {
return tree.modifiers().annotations().stream()
.anyMatch(annotation -> annotation.symbolType().is(BEAN_ANNOTATION));
}

/*
* A method with the prototype scope is meant to return a new instance on every call.
*/
Expand Down

0 comments on commit 97258b1

Please sign in to comment.