首页 > 解决方案 > Spring JPA 数据:自定义通用存储库和服务:UnsatisfiedDependencyException

问题描述

我正在为许多实体提供宁静的服务。如果我们考虑两组父资源子资源,两个组成员在其组范围内对 CRUD 操作具有相同的实现。

因此,每一层不仅有一个通用类。这是我的代码:

存储库:

具有所有实体使用的方法的基础存储库:

@Repository
public interface GenericRepository<T, ID extends Serializable> extends JpaRepository<T, ID> {
    Page<T> findAll(Pageable pageable);
}

父亲资源

@Repository
public interface EntityGenericRepository<T, ID extends Serializable> extends GenericRepository<T, ID> {
    T findByName(String name);
}

子资源

@Repository
public interface NestedEntityGenericRepository<T, ID extends Serializable> extends GenericRepository<T, ID> {
    Page<T> findByFatherId(ID fatherId, Pageable pageable);
}

服务:

基地:

public interface GenericService<T,ID extends Serializable> {
    Page<T> findAll(int page, int size);

    T findById(ID id);
}

给父亲:

public interface EntityGenericService<T, ID extends Serializable> extends GenericService<T, ID> {
    T findByName(String name);

    T save(T t);

    void update(ID id, T t);

    void softDelete(ID id);
}

对于孩子:

public interface NestedEntityGenericService<T, ID extends Serializable> {
    Page<T> findBySensorId(ID fatherId, int page, int size);

    T save(ID fatherId, T t);

    void update(ID fatherId, ID id, T t);

    void softDelete(ID fatherId, ID id);
}

服务实施:

根据:

@Service
public class GenericServiceImpl<T,ID extends Serializable>
        implements GenericService<T,ID> { //codes }

给父亲:

@Service
public class EntityGenericServiceImpl<T, ID extends Serializable>
        extends GenericServiceImpl<T, ID>
        implements EntityGenericService<T, ID> {//codes}

对于孩子:

@Service
public class NestedEntityGenericServiceImpl<T, U, ID extends Serializable>
        extends EntityGenericServiceImpl<T, ID>
        implements NestedEntityGenericService<T, ID> {//codes}

当我运行它时,它只会抛出UnsatisfiedDependencyException. 整个消息:

Exception encountered during context initialization - cancelling refresh attempt: 
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating 
bean with name 'entityGenericServiceImpl': Unsatisfied dependency expressed through 
field 'genericRepository': Error creating bean with name 'nestedEntityGenericRepository': 
Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: 
Not a managed type: class java.lang.Object; nested exception is 
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 
'nestedEntityGenericRepository': Invocation of init method failed; nested exception is 
java.lang.IllegalArgumentException: Not a managed type: class java.lang.Object

搜索了很多,但没有找到解决此问题的方法。任何帮助表示赞赏

问候

标签: javaspring-bootspring-data-jpageneric-programming

解决方案


我通过为每个实体创建具体的存储库来解决这个问题。我试图减少课程的数量。因此,我定义了 3 个通用存储库来完成定义为服务所有实体的所有其他存储库的工作。但是我知道这是不可能的,并且必须在自定义存储库的最后一级定义具体的存储库,以便与服务层进行交互。

原因是反思。Spring 使用反射来完成所有幕后工作,它必须知道它必须为哪个实体使用提供者(Hibernate)

需要注意的是,如果要创建通用服务层,它的最后一层也必须有具体的实现。因为具体的存储库必须在某处声明


推荐阅读