Spring Boot Maven打包前执行clean install报错:找不到@SpringBootConfiguration
Hey there! I see you're hitting this error when trying to build your Spring Boot jar with mvn clean install—totally understandable as a new Spring Boot dev, especially since that test class was auto-generated for you. Let's break down why this happens and how to fix it quickly.
Why This Error Happens
The @SpringBootTest annotation needs to locate your main Spring Boot configuration class (the one with @SpringBootApplication on it) to set up the test context. By default, it looks in the same package as your test class (or subpackages) for this configuration. If it can't find it—maybe your main class is in a mismatched package, or there's a structure issue—you get this error.
Solution 1: Point the Test to Your Main Configuration Class
The simplest fix is to explicitly tell @SpringBootTest which class is your main configuration. Update your test class like this:
package com.Alex.demo; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; // Import your main Spring Boot application class import com.Alex.demo.WebAppApplication; @SpringBootTest(classes = WebAppApplication.class) class WebAppApplicationTests { @Test void contextLoads() { } }
Make sure your main application class has the @SpringBootApplication annotation (it should, since it's auto-generated too):
package com.Alex.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class WebAppApplication { public static void main(String[] args) { SpringApplication.run(WebAppApplication.class, args); } }
Solution 2: Skip Tests Entirely (If You Don't Need Them Right Now)
Since you mentioned you haven't used the test functionality yet, you can tell Maven to skip running tests during the build. Use one of these commands:
mvn clean install -DskipTests: This compiles your test classes but skips running them.mvn clean install -Dmaven.test.skip=true: This skips both compiling and running tests (faster if you don't plan to touch tests soon).
Pro Tip for Future Testing
Once you start writing tests, keep your test classes in the same package structure as your main application classes. For example, if your main service class is in com.Alex.demo.service, put its test class in com.Alex.demo.service. This way, @SpringBootTest will automatically find your configuration without needing the classes parameter.
内容的提问来源于stack exchange,提问作者Fenzox

