我正在寻找一种存储我的对象的方法,似乎最好的方法是使用代理.我在互联网上找到了2个注释,我应该使用哪个注释:
@Scope(value = "session", proxyMode = ScopedProxyMode.INTERFACES)
Run Code Online (Sandbox Code Playgroud)
要么
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS )
Run Code Online (Sandbox Code Playgroud)
此外,代理是否是使用@Component
@Scope("session")或使用的最佳方式@SessionAttributes?
正如我们所知道Spring使用代理来增加功能(@Transactional和@Scheduled举例)。有两种选择-使用JDK动态代理(该类必须实现非空接口),或使用CGLIB代码生成器生成子类。我一直认为proxyMode允许我在JDK动态代理和CGLIB之间进行选择。
但是我能够创建一个示例,说明我的假设是错误的:
单身人士:
@Service
public class MyBeanA {
@Autowired
private MyBeanB myBeanB;
public void foo() {
System.out.println(myBeanB.getCounter());
}
public MyBeanB getMyBeanB() {
return myBeanB;
}
}
Run Code Online (Sandbox Code Playgroud)
原型:
@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;
}
} …Run Code Online (Sandbox Code Playgroud)