Home > other >  Why can't @Autowired a JPA repository - Spring boot JPA
Why can't @Autowired a JPA repository - Spring boot JPA

Time:01-25

I'm giving this error:

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.

The controller:

@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)
        );
    }

}

The Application Layer:

@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);
    }
}

In the Infrastructure layer

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

}

The boot Application:


@EnableJpaRepositories
@SpringBootApplication
public class MicroserviceApplication {

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

}

All dependencies are resolved and the others classes I believe that are irrellevant.

Any suggestions? Thank you very much

CodePudding user response:

Probably, the error cause is HibernateJpaRepository - it has to be an interface that extends JpaRepository.

CodePudding user response:

You could write your own Repository in a interface:

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

Then your Class:

@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);
    }
}
  •  Tags:  
  • Related