编写自定义范围来执行此操作非常容易......
public class CustomScope implements Scope, BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
String name = "myScope";
beanFactory.registerScope(name, this);
Assert.state(beanFactory instanceof BeanDefinitionRegistry,
"BeanFactory was not a BeanDefinitionRegistry, so CustomScope cannot be used.");
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
for (String beanName : beanFactory.getBeanDefinitionNames()) {
BeanDefinition definition = beanFactory.getBeanDefinition(beanName);
if (name.equals(definition.getScope())) {
BeanDefinitionHolder proxyHolder = ScopedProxyUtils.createScopedProxy(new BeanDefinitionHolder(definition, beanName), registry, false);
registry.registerBeanDefinition(beanName, proxyHolder.getBeanDefinition());
}
}
}
@Override
public Object get(String name, ObjectFactory<?> objectFactory) {
return objectFactory.getObject(); // a new one every time
}
@Override
public String getConversationId() {
return null;
}
@Override
public void registerDestructionCallback(String name, Runnable callback) {
}
@Override
public Object remove(String name) {
return null;
}
@Override
public Object resolveContextualObject(String arg0) {
return null;
}
}
public class Foo implements MessageListener {
private Bar bar;
public void setBar(Bar bar) {
this.bar = bar;
}
@Override
public void onMessage(Message message) {
System.out.println(bar.getId());
}
}
@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
public class FooTests {
@Autowired
private Foo foo;
@Test
public void test() {
Message message = mock(Message.class);
foo.onMessage(message);
foo.onMessage(message);
}
}
和一个示例上下文...
<bean class="foo.CustomScope" />
<bean id="baz" class="foo.BazImpl" scope="myScope" />
<bean id="bar" class="foo.BarImpl" scope="myScope">
<property name="baz" ref="baz" />
</bean>
<bean id="foo" class="foo.Foo">
<property name="bar" ref="bar" />
</bean>
注意:使用这个简单的范围,您还必须将所有引用的 bean 放在范围内(上面的 bar和baz)。您可以使所有引用的 bean 都继承范围,但这需要一些工作。也就是说 - 在 spring-batch 的 StepScope 中有一个如何做到这一点的例子。
注意#2这将为每个方法调用获取一个新实例。如果调用多个方法,每次调用都会获得一个新 bean。如果您想将其范围限定为允许 onMessage 中的所有调用使用相同的实例,则需要添加更多技巧。
编辑:
这里有一些更新支持对 onMessage() 中的一个实例的多次调用...
private final ThreadLocal<Map<String, Object>> holder = new ThreadLocal<Map<String, Object>>();
...
@Override
public Object get(String name, ObjectFactory<?> objectFactory) {
Map<String, Object> cache = this.holder.get();
if (cache == null) {
cache = new HashMap<String, Object>();
this.holder.set(cache);
}
Object object = cache.get(name);
if (object == null) {
object = objectFactory.getObject();
cache.put(name, object);
}
return object;
}
public void clearCache() {
this.holder.remove();
}
现在,您确实必须清除缓存...
@Override
public void onMessage(Message message) {
try {
System.out.println(bar.getId());
System.out.println(bar.getId());
}
finally {
this.scope.clearCache();
}
}
但即使这样也可以在 AOP @After 建议中完成,以保持听众完全干净。