Spring Boot自动配置库创建失败:HelloService Bean无法找到
问题描述
我有两个Spring Boot 3.0.5项目:一个是类库spring-lib,另一个是引用该类库的Web应用。尝试通过自动配置让Web应用注入类库中的HelloService,但启动时提示找不到该Bean。
类库代码
配置类HelloConfiguration(com.example.springlib.configuration包):
@Configuration @ConfigurationProperties(prefix = "com.example.hello") public class HelloConfiguration { private String text; @Bean public HelloService helloService() { return new HelloService(text); } }
服务类HelloService(com.example.springlib.service包):
@RequiredArgsConstructor public class HelloService { private final String hello; public String hello(String name) { return String.format(hello, name); } }
类库中配置的自动配置文件META-INF/spring.factories:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.example.springlib.configuration.HelloConfiguration
Web应用代码
控制器HelloController(com.example.springweb.web包):
@RestController @RequiredArgsConstructor public class HelloController { private final HelloService helloService; @GetMapping("/hello/{name}") public HelloResponse convert(@PathVariable String name) { var response = new HelloResponse(); response.setMessage(helloService.hello(name)); return response; } }
Web应用application.yml配置:
com: example: hello: text: Hello %s!
报错信息
Description: Parameter 0 of constructor in com.example.springweb.web.HelloController required a bean of type 'com.example.springlib.service.HelloService' that could not be found.
问题原因及解决方法
1. Spring Boot 3.x 自动配置注册方式变更
Spring Boot 3.x基于Spring 6,已废弃META-INF/spring.factories作为自动配置类的注册入口,改用META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports文件。
修复步骤:
- 在类库的
src/main/resources/META-INF/spring/目录下创建文件org.springframework.boot.autoconfigure.AutoConfiguration.imports - 文件内直接写入配置类的全限定名:
com.example.springlib.configuration.HelloConfiguration
2. 配置属性未正确绑定
HelloConfiguration中的text属性没有setter方法,@ConfigurationProperties无法将配置文件中的值绑定到该属性,最终会导致HelloService的hello字段为null。
修复步骤:
- 给
text属性添加setter方法,或使用Lombok的@Setter注解:
若不使用Lombok,可手动添加setter:@Configuration @ConfigurationProperties(prefix = "com.example.hello") @Setter // 需引入Lombok依赖 public class HelloConfiguration { private String text; @Bean public HelloService helloService() { return new HelloService(text); } }public void setText(String text) { this.text = text; }
3. 确认类库依赖引入正确
检查Web应用的构建文件(pom.xml或build.gradle),确保spring-lib依赖已正确引入,且依赖范围为compile(默认范围,确保编译和运行时均可获取类库文件)。
完成以上修改后,重新构建类库并启动Web应用,调用/hello/Bob即可返回预期的Hello Bob!。
内容的提问来源于stack exchange,提问作者Jean-François Beauchef

