正如我们所知,Spring使用代理来添加功能(例如@Transactional
和@Scheduled
)。有两个选项 - 使用JDK动态代理(类必须实现非空接口),或者使用CGLIB代码生成器生成子类。我一直认为proxyMode允许我在JDK动态代理和CGLIB之间进行选择。
但是我成功创建了一个示例,证明我的假设是错误的:
案例1:
单例模式:
@Service
public class MyBeanA {
@Autowired
private MyBeanB myBeanB;
public void foo() {
System.out.println(myBeanB.getCounter());
}
public MyBeanB getMyBeanB() {
return myBeanB;
}
}
原型:
@Service
@Scope(value = "prototype")
public class MyBeanB {
private static final AtomicLong COUNTER = new AtomicLong(0);
private Long index;
public MyBeanB() {
index = COUNTER.getAndIncrement();
System.out.println("constructor invocation:" + index);
}
@Transactional // just to force Spring to create a proxy
public long getCounter() {
return index;
}
}
主要内容:
MyBeanA beanA = context.getBean(MyBeanA.class);
beanA.foo();
beanA.foo();
MyBeanB myBeanB = beanA.getMyBeanB();
System.out.println("counter: " + myBeanB.getCounter() + ", class=" + myBeanB.getClass());
输出:
constructor invocation:0
0
0
counter: 0, class=class test.pack.MyBeanB$$EnhancerBySpringCGLIB$$2f3d648e
这里我们可以看到两件事情:
MyBeanB
只被实例化一次。- 为
MyBeanB
添加@Transactional
功能时,Spring使用了CGLIB。
案例2:
让我更正一下MyBeanB
的定义:
@Service
@Scope(value = "prototype", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class MyBeanB {
在这种情况下,输出为:
constructor invocation:0
0
constructor invocation:1
1
constructor invocation:2
counter: 2, class=class test.pack.MyBeanB$$EnhancerBySpringCGLIB$$b06d71f2
我们可以看到两件事:
- 实例化了
MyBeanB
3 次。 - 为了给
MyBeanB
添加@Transactional
功能,Spring使用了CGLIB。
您能解释一下发生了什么吗?代理模式是如何工作的呢?
P.S.
我已经阅读过文档:
/**
* Specifies whether a component should be configured as a scoped proxy
* and if so, whether the proxy should be interface-based or subclass-based.
* <p>Defaults to {@link ScopedProxyMode#DEFAULT}, which typically indicates
* that no scoped proxy should be created unless a different default
* has been configured at the component-scan instruction level.
* <p>Analogous to {@code <aop:scoped-proxy/>} support in Spring XML.
* @see ScopedProxyMode
*/
但对我来说还不太清楚。
更新
案例3:
我调查了另一个案例,在这个案例中,我从MyBeanB
中提取了接口:
public interface MyBeanBInterface {
long getCounter();
}
@Service
public class MyBeanA {
@Autowired
private MyBeanBInterface myBeanB;
@Service
@Scope(value = "prototype", proxyMode = ScopedProxyMode.INTERFACES)
public class MyBeanB implements MyBeanBInterface {
在这种情况下,输出结果为:
constructor invocation:0
0
constructor invocation:1
1
constructor invocation:2
counter: 2, class=class com.sun.proxy.$Proxy92
这里有两个要点:
MyBeanB
实例化了3次。- 为了为
MyBeanB
添加@Transactional
功能,Spring 使用了 JDK 动态代理。
MyBeanB
类没有扩展任何接口,因此您的控制台日志显示CGLIB代理实例并不奇怪。在情况3中,您引入并实现了一个接口,因此您会得到一个JDK代理。您甚至在介绍性文本中描述了这一点。 - kriegaex