SpringBoot项目无法自动装配Service与Repository问题求助
执行mvn clean install时测试阶段报错,具体错误信息如下:
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 5.805 s <<< FAILURE! - in ---myprojectpath---
contextLoads Time elapsed: 0.001 s <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myController': Unsatisfied dependency expressed through field 'myService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myServiceImpl': Unsatisfied dependency expressed through field 'myRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type '---myprojectpath---' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myServiceImpl': Unsatisfied dependency expressed through field 'myRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type '---myprojectpath---' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type '---myprojectpath---' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
忽略错误完成构建后,运行项目仍会出现其他问题,推测解决此测试错误即可解决全部问题。
代码片段
控制器代码
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping("/Mycontroller") public class Mycontroller{ private static final Logger LOGGER = LoggerFactory.getLogger(Mycontroller.class); ObjectMapper mapper = new ObjectMapper(); @Autowired private MyService MyService ; @GetMapping(value = "/getDatas", produces = "application/json") public ResponseEntity getDatas() { try { DataList responseEntity = new DataList (); List<Data> datas= MyService.getDatasBean(); .......... } catch (Exception e) { .......... } } }
Service接口
public interface MyService { List<Data> getDatasBean() throws Exception; }
Service实现类
import org.slf4j.Logger;import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.persistence.NoResultException; import java.util.List; @Service @Transactional(readOnly = false) public class MyServiceImpl implements MyService{ private static final Logger LOGGER = LoggerFactory.getLogger(MyServiceImpl.class); @Autowired private MyRepository MyRepository ; public List<Data> getDatasBean() throws Exception { LOGGER.info(String.format("looking for datas")); try { return MyRepository.getAllDatas(); } catch (NoResultException e) { return null; } catch (IllegalStateException | IllegalArgumentException e) { throw new Exception(e); //throw new BackOfficeEntityException(String.format("error"), e); } } }
Repository代码
import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface MyRepository extends CrudRepository<Data, Long> { @Query("SELECT a " +"FROM Data a ") List<Data> getAllDatas(); }
pom.xml配置
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven 4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.7.1</version> <relativePath/> <!-- lookup parent from repository --> </parent> <artifactId>Myproject-jpa</artifactId> <packaging>jar</packaging> <name>Myproject-jpa</name> <dependencies> <dependency> <groupId>com.oracle.database.jdbc</groupId> <artifactId>ojdbc8</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.12.4</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-jpa</artifactId> <version>3.0.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>5.3.14</version> </dependency> <dependency> <groupId>jakarta.persistence</groupId> <artifactId>jakarta.persistence-api</artifactId> <version>2.2.3</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.6.1</version> <configuration> <source>11</source> <target>11</target> <annotationProcessorPaths> <path> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-processor</artifactId> <version>1.4.2.Final</version> </path> </annotationProcessorPaths> </configuration> </plugin> </plugins> </build> </project>
已尝试操作
- 执行过Maven的clean、validate、compile、test等步骤,均出现上述错误
- 修改过pom.xml依赖,未解决问题
排查建议
- 包扫描范围问题:检查SpringBoot启动类的
@SpringBootApplication注解是否覆盖Repository、Service、Controller所在的包。若启动类与这些组件不在同一父包下,需手动添加@EnableJpaRepositories(basePackages = "xxx")指定Repository路径,同时确保@ComponentScan覆盖Service和Controller的包。 - 依赖版本冲突:Spring Boot 2.7.1对应的Spring Data JPA版本为2.7.x,手动引入的3.0.0版本会导致不兼容。删除
<dependency>org.springframework.data:spring-data-jpa:3.0.0</dependency>,直接使用spring-boot-starter-data-jpa提供的依赖即可。 - Repository与实体类配置:确认
Data实体类添加了@Entity和@Id注解,JPA才能识别实体,进而初始化Repository。同时检查Repository接口的@Repository注解是否正确,继承CrudRepository的泛型参数是否对应正确。 - 测试类配置:若测试阶段报错,检查测试类是否添加
@SpringBootTest注解,且测试类的包路径与启动类一致,确保测试环境能正确加载ApplicationContext。
内容的提问来源于stack exchange,提问作者pietro99

