【问题标题】:Why can't @Autowired a JPA repository - Spring boot + JPA为什么不能@Autowired 一个 JPA 存储库 - Spring boot + JPA
【发布时间】:2022-01-24 12:05:27
【问题描述】:

我给出了这个错误:

Parameter 0 of constructor in x.microservice.module.business.application.BusinessCreator required a bean of type 'x.microservice.module.business.infrastructure.HibernateJpaRepository' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=false)


Action:

Consider defining a bean of type 'x.microservice.module.business.infrastructure.HibernateJpaRepository' in your configuration.

控制器:

@Slf4j
@RestController
public final class BusinessPostController {

    @Autowired
    private BusinessCreator creator;

    @PostMapping(value = "/business")
    public ResponseEntity create(@RequestBody Request request){
        BusinessCreatorDto businessCreatorDto = new BusinessCreatorDto(IdentifierEpoch.generate(),request.getName());
        return ResponseEntity.ok(
                creator.create(businessCreatorDto)
        );
    }

}

应用层:

@AllArgsConstructor
@Service
public class BusinessCreator {

    @Autowired
    private HibernateJpaRepository repository;

    public BusinessResponse create(BusinessCreatorDto dto){

        Business business = new Business(dto.getId(), dto.getName());
        repository.save(business);

        return BusinessResponse.fromAggregate(business);
    }
}

在基础设施层

@Repository
public abstract class HibernateJpaRepository implements JpaRepository<Business, Long> {

}

启动应用程序:


@EnableJpaRepositories
@SpringBootApplication
public class MicroserviceApplication {

    public static void main(String[] args) {
        SpringApplication.run(MicroserviceApplication.class, args);
    }

}

所有依赖项都已解决,我认为其他类无关紧要。

有什么建议吗?非常感谢

【问题讨论】:

  • 你有spring-boot-starter-data-jpa 依赖吗?您的存储库、服务、控制器是否都位于(包含配置文件的文件夹)下
  • 错误出现在我的存储库中,我已更改为:@Repository public interface HibernateJpaRepository extends JpaRepository { } 现在运行正常。谢谢。

标签: spring-boot spring-data-jpa


【解决方案1】:

错误原因可能是HibernateJpaRepository - 它必须是扩展JpaRepository 的接口。

【讨论】:

    【解决方案2】:

    您可以在界面中编写自己的存储库:

    @Repository
    public interface HibernateJpaRepository extends JpaRepository < Business, Long > {
    }
    

    然后你的班级:

    @AllArgsConstructor
    @Service
    public class BusinessCreator {
    
        @Autowired
        private HibernateJpaRepository repository;
    
        public BusinessResponse create(BusinessCreatorDto dto){
    
            Business business = new Business(dto.getId(), dto.getName());
            repository.save(business);
    
            return BusinessResponse.fromAggregate(business);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-04-23
      • 2021-11-07
      • 2017-11-13
      • 2022-10-13
      • 2018-08-06
      • 2021-04-16
      • 2015-12-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多