Skip to content

Commit

Permalink
Keep @Autowired on classes annotated with @ConfigurationProperties
Browse files Browse the repository at this point in the history
  • Loading branch information
timtebeek committed Jan 15, 2024
1 parent 71fbf7c commit d39cf28
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import org.openrewrite.java.AnnotationMatcher;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.RemoveAnnotationVisitor;
import org.openrewrite.java.search.FindAnnotations;
import org.openrewrite.java.search.UsesType;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.Statement;
Expand Down Expand Up @@ -59,6 +60,11 @@ public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, Ex
}
}

// `@ConfigurationProperties` classes usually use field injection, so keep `@Autowired` on constructors
if (!FindAnnotations.find(cd, "@org.springframework.boot.context.properties.ConfigurationProperties").isEmpty()) {
return cd;
}

return cd.withBody(cd.getBody().withStatements(
ListUtils.map(cd.getBody().getStatements(), s -> {
if (!isConstructor(s)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ class NoAutowiredOnConstructorTest implements RewriteTest {
@Override
public void defaults(RecipeSpec spec) {
spec.recipe(new NoAutowiredOnConstructor())
.parser(JavaParser.fromJavaVersion().classpath("spring-beans", "spring-context", "spring-core"));
.parser(JavaParser.fromJavaVersion().classpath("spring-beans", "spring-boot", "spring-context", "spring-core"));
}

@Issue("https://github.com/openrewrite/rewrite-spring/issues/78")
Expand Down Expand Up @@ -538,4 +538,26 @@ public DatabaseConfiguration(DataSource dataSource) {
)
);
}

@Test
void ignoreConfigurationProperties() {
//language=java
rewriteRun(
java(
"""
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.env.Environment;
@ConfigurationProperties
public class ArchivingWorkflowListenerProperties {
private final Environment environment;
@Autowired
public ArchivingWorkflowListenerProperties(Environment environment) {
this.environment = environment;
}
}
"""
)
);
}
}

0 comments on commit d39cf28

Please sign in to comment.