@Lazy批注和< bean />的lazy-init属性有什么区别?标签? [英] What's the difference between @Lazy annotation and lazy-init attribute of <bean/> tag?
问题描述
据我了解,标签的@Lazy批注和lazy-init属性应具有相同的功能。但是,当我开发以下代码时,它表现出独特的行为。
在以下代码中,我期望:-(循环依赖项错误)
As per my understanding, @Lazy annotation and lazy-init attribute of tag should have the same functionality. But when I developed the following code, it's showing distinct behaviours. In the following code, I was expecting :- (Circular Dependency Error)
org.springframework.beans.factory.BeanCurrentlyInCreationException
org.springframework.beans.factory.BeanCurrentlyInCreationException
我已经使用@Lazy注释附加了代码,按照我的期望,它不应允许循环依赖。
I have attached code using @Lazy annotation, as per my expectations it should not allow Circular Dependency.
@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);
}
}
Spring配置文件:
<?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>
输出:-
AA()-1参数构造函数
A.A() - 1-param Constructor
BB()-1参数构造函数
B.B() - 1-param Constructor
需要解释,为什么会这样?
推荐答案
来自 Spring框架文档:
...您还可以将
@Lazy
注释放置在标记为
且带有@Autowired
或@Inject
。在这种情况下,它会导致注入
的惰性解析代理。
... you can also place the
@Lazy
annotation on injection points marked with@Autowired
or@Inject
. In this context, it leads to the injection of a lazy-resolution proxy.
因此,在以下代码中:
So, in the following code:
@Autowired
public A(@Lazy B b) {
// ...
}
b
(
现在,如果您将代码更改为以下内容,则只需在 上自动连接)。
Now, if you change your code to the following:
@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
。
这篇关于@Lazy批注和< bean />的lazy-init属性有什么区别?标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!