应用程序上下文中某些bean的依赖关系形成一个循环

Lau*_*let 10 java spring spring-data-jpa spring-boot

我正在使用JPA开发Spring Boot v1.4.2.RELEASE应用程序.

我定义了存储库接口和实现

ARepository

@Repository
public interface ARepository extends CrudRepository<A, String>, ARepositoryCustom, JpaSpecificationExecutor<A> {
}
Run Code Online (Sandbox Code Playgroud)

ARepositoryCustom

@Repository
public interface ARepositoryCustom {
    Page<A> findA(findAForm form, Pageable pageable);
}
Run Code Online (Sandbox Code Playgroud)

ARepositoryImpl

@Repository
public class ARepositoryImpl implements ARepositoryCustom {
    @Autowired
    private ARepository aRepository;
    @Override
    public Page<A> findA(findAForm form, Pageable pageable) {
        return aRepository.findAll(
                where(ASpecs.codeLike(form.getCode()))
                .and(ASpecs.labelLike(form.getLabel()))
                .and(ASpecs.isActive()),
                pageable);
    }
}
Run Code Online (Sandbox Code Playgroud)

和服务 AServiceImpl

@Service
public class AServiceImpl implements AService {
    private ARepository aRepository;
    public AServiceImpl(ARepository aRepository) {
        super();
        this.aRepository = aRepository;
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

我的应用程序不会以消息开头:

***************************
APPLICATION FAILED TO START
***************************

Description:

The dependencies of some of the beans in the application context form a cycle:

|  aRepositoryImpl
???????

我按照http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.single-repository-behaviour中描述的所有步骤进行了操作

请帮忙 !

洛朗

小智 16

@Lazy

打破循环的一种简单方法是说 Spring 懒惰地初始化其中一个 bean。也就是说:它不会完全初始化 bean,而是创建一个代理以将其注入另一个 bean。注入的 bean 只有在第一次需要时才会完全创建。

@Service
public class AServiceImpl implements AService {
    private final ARepository aRepository;
    public AServiceImpl(@Lazy ARepository aRepository) {
        super();
        this.aRepository = aRepository;
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

来源:https : //www.baeldung.com/circular-dependencies-in-spring


小智 13

使用@Lazy注解即可解决

@Component
public class Bean1 {
    @Lazy
    @Autowired
    private Bean2 bean2;
}
Run Code Online (Sandbox Code Playgroud)


And*_*sel 6

对原始问题有一个简单的解决方法:只需从ARepositoryCustom和ARepositoryImpl中删除@Repository即可.保留所有命名和接口/类层次结构.一切都好.