gpt4 book ai didi

java - spring中通过@Inject递归调用自己的类

转载 作者:行者123 更新时间:2023-12-01 10:40:27 26 4
gpt4 key购买 nike

@Named
@Scope(value = "prototype")
public class Product extends Factory

{
@Inject
protected Product product;

protected void something(){}

protected void thatThing(){

}

抛出以下异常

found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@javax.inject.Inject()} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java :292) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304) Truncated. see log file for complete stacktrace

最佳答案

如果范围设置为原型(prototype),Spring IoC 容器每次发出对该特定 bean 的请求时都会创建该对象的新 bean 实例。

在您的代码中,您有一个成员产品。因此,每当您需要新产品时,框架都会创建一个新的产品成员实例。并且递归地,该成员将再次创建它的成员。所以这显然是不妥当的。

我想,也许应该是这样的:

@Named
public class ProductBuilder extends Factory {

@Inject
protected Product product;

protected void something(){}

protected void thatThing(){

}

然后对于您的产品,将 bean 定义为原型(prototype):

@Scope(value = "prototype")
public class Product {
....
}

关于java - spring中通过@Inject递归调用自己的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34449170/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com