【发布时间】:2013-06-25 12:48:13
【问题描述】:
我有一个叫做Executor的spring bean我需要这个执行器被注入到两个类中,一个是会话范围的,另一个是单例的,所以我使用@Autowired注解在两个类中注入它,它工作得很好,但是对于会话 bean,执行器只是所有会话的一个,我知道它应该是这样工作的。
我怎样才能让 executor 获得注入的 bean 的范围?现在我所能做的就是为每个类使用两个不同的类。
而且我无法真正理解在中设置属性scoped-proxy 的效果
<context-component-scan /> 到 targetClass。
编辑
这是我对原型范围的尝试:
假设这是我的会话 soped bean
@Component
@Scope("session")
public class WebExecutor(){
@Autowired
private ExecutorService executor;
@Async
public void startCalc(){
executor.start("now");
}
}
这是我的 ExecutorService 类
@Component
@Scope("prototype")
public class ExecutorService{
private int progress;
public void start(String when){
//do some stuff and increment the progress
}
//getter and setter for progress
}
我还有另一个具有默认单例范围的组件,它也自动装配执行器,因此执行器不能是会话范围。
所以现在我有一个类需要拥有它正在自动装配的 bean 的范围,所以我尝试了原型范围。
这在 Web 版本中应该如何工作是这样的
- 您单击一个链接开始执行调用
WebExecutor的方法start - 然后我使用 WebParser 从 ExecutorService 获取进度并将其传回给用户以报告进度。
这在原型之前运行良好,但 ExecutorService 是所有会话之一,
所以我使用原型,但现在进度始终为 0,当我调试 Executor 时,我发现它正在递增,但显然 WebExecutor 看不到递增。
【问题讨论】:
标签: spring spring-mvc scope javabeans