Spring Boot项目IDE运行正常但打JAR包启动找不到Bean报错如何解决
问题解决方案
1. 调整包扫描配置或启动类位置
Spring Boot默认仅扫描启动类所在包及其子包下的Bean,若启动类不在业务类的根包com.xxx.wfmDriverservice下,会导致扫描不到对应的@RestController、@Service注解类。
- 优先将启动类移动到
com.xxx.wfmDriverservice根包路径下 - 若不移动启动类,在启动类上添加注解配置全量扫描路径:
@SpringBootApplication(scanBasePackages = "com.xxx.wfmDriverservice") // 若使用MyBatis等持久层框架,同步补充对应的扫描配置,例如 // @MapperScan("com.xxx.wfmDriverservice.mapper")
2. 修正Gradle打包配置
你使用的Gradle 6.8.3与Spring Boot 2.4.3搭配时,需确保打包配置正确:
- 检查
build.gradle是否引入了正确的Spring Boot插件:
plugins { id 'java' id 'org.springframework.boot' version '2.4.3' id 'io.spring.dependency-management' version '1.0.11.RELEASE' }
- 打包时执行
bootJar任务而非默认的jar任务,可通过命令./gradlew clean bootJar执行打包,生成的可执行JAR包默认输出在build/libs目录下 - 检查
sourceSets配置,确保main目录下的java源码被正确纳入编译范围,避免出现源码未打包进JAR的问题
3. 检查类定义与依赖配置
- 确认
DriverServiceImp类的访问修饰符为public,避免跨包访问时类加载失败 - 检查依赖冲突:执行
./gradlew dependencies查看依赖树,排除重复或版本冲突的Spring相关依赖,IDEA运行时的类加载优先级与JAR包运行时的LaunchedURLClassLoader加载优先级不同,容易出现IDEA正常、打包后报错的依赖冲突问题 - 确认
RestDriver类中注入driverService的注解配置正确,若使用字段注入需添加@Autowired注解,若使用构造注入需确保构造方法符合规范
项目结构参考

报错信息回顾
2021-10-21 12:04:45 [main] ERROR o.s.boot.SpringApplication at 856 - Application run failed org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'restDriver': Unsatisfied dependency expressed through field 'driverService'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'DriverService': Lookup method resolution failed; nested exception is java.lang.IllegalStateException: Failed to introspect Class [com.xxx.wfmDriverservice.service.DriverServiceImp] from ClassLoader [org.springframework.boot.loader.LaunchedURLClassLoader@5c7fa833]
内容的提问来源于stack exchange,提问作者humbleSquid
相关产品推荐
相关产品推荐

