根据我的理解,@Lazy注释和标签的lazy-init属性应该具有相同的功能。但是当我开发以下代码时,它显示出不同的行为。
在下面的代码中,我期待:-(循环依赖错误)
org.springframework.beans.factory.BeanCurrentlyInCreationException
我已使用 @Lazy 注释附加了代码,根据我的期望,它不应允许循环依赖。
@Component
public class A {
private B b;
@Autowired
public A(@Lazy B b) {
System.out.println("A.A() - 1-param Constructor");
this.b = b;
}
}
@Component
public class B {
private A a;
@Autowired
public B(A a) {
System.out.println("B.B() - 1-param Constructor");
this.a = a;
}
}
主要类别:
public class AnnotationApp{
public static void main(String[] args){
ApplicationContext ctx = new ClassPathXmlApplicationContext("com/ry/cfgs/annotationAppContext.xml");
B objB = ctx.getBean("b", B.class);
A objA = ctx.getBean("a", A.class);
}
}
弹簧配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<context:component-scan base-package="com.ry.beans.annotation"></context:component-scan>
</beans>
输出 :-
A.A() - 1 参数构造函数
B.B() - 1 参数构造函数
需要解释一下,为什么会这样?
From Spring框架文档 https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#beans-factorybeans-annotations:
...您还可以将@Lazy
标注注入点的注释
和@Autowired
or @Inject
。在这种情况下,它会导致注入
惰性解析代理的。
所以,在下面的代码中:
@Autowired
public A(@Lazy B b) {
// ...
}
b
将被注入(自动装配)首次访问而不是在启动时。
现在,如果您将代码更改为以下内容:
@Autowired
public A(@Lazy B b) {
System.out.println("A.A() - 1-param Constructor");
System.out.println(b.toString());
this.b = b;
}
你会看到org.springframework.beans.factory.BeanCurrentlyInCreationException
被抛出。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)