spring bean循环引用问题

 
 
在spring容器启动的过程中报如下错误: 2017-07-04 07:09:53.231 WARN [bi-service-recom-server,,,] 1 --- [ main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'recomController': Unsatisfied dependency expressed through field 'recommService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'recommService': Unsatisfied dependency expressed through field 'personalizedABRouteTable'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'ABTestConf': Unsatisfied dependency expressed through field 'personalizedABRouteTable'; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'personalizedABRouteTable': Requested bean is currently in creation: Is there an unresolvable circular reference?


检查发现并没有循环依赖的bean,再查看一下最后一个错误信息的类:

@Component
public class MyClass {
       @Autowired
       PersonalizedABRouteTable personalizedABRouteTable;

       @Bean("personalizedABRouteTable")
    public PersonalizedABRouteTable getPersonalizedABRouteTable() {
        PersonalizedABRouteTable table = new PersonalizedABRouteTable();
        table.orderedRuleList = personalizedRouteRules;
        return table;
    }
}

发现了问题所在。spring在类加载的时候,有两类方式获取bean,一是通过@autowired等标签注入装载到容器的bean;还有一种方式是使用@bean等标签通知spring容器生成一个指定的bean。

在这里PersonalizedABRouteTable并不在spring容器中初始化的时候生成,而是使用MyClass的@bean标签生成,之后注入到类中。

但是这两种方式尽量不要混用。在上述例子中只被初始化一次不会有问题,一旦另外一个类同样需要注入PersonalizedABRouteTable,则容器初始化bean的时候就会产生循环依赖,另外一个类一直在等待MyClass初始化生成PersonalizedABRouteTable,而MyClass又没有装载完成,因此产生了circle reference。

将@Autowired注释去掉后,问题解决。

从另外一个层面讲,将@bean注解去掉,使用@PostConstruct注解,通过applicationContext获取bean,交给MyClass后,同样不会循环依赖。原理是相通的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值