背景
在我们的项目中,通过Spring来管理业务逻辑Bean,但是Spring Bean的作用域默认是单例,而有时候我们的业务逻辑Bean不是线程安全的,所以需要将Spring Bean改为多例模式。
分析
为单个Bean设置单例或者多例,可以通过设置singleton属性,见以下代码:
<bean id="page" class="com.daks.action.LoginAction" singleton="false"/>
但是我们没有一个一个Bean进行配置,而是通过context:component-scan自动扫描@Component注释来装载Bean。所以我们需要1 直接修改Spring整个Bean容器的Bean默认作用域,或者2 修改某一个扫描的包下的所有Bean的作用域。这里第一种思路没有找到答案,据说早期的Spring版本允许设置全局Bean默认作用域,后来的版本已经不再允许。下面为第二种思路找到了方案,重要在于context:component-scan标签中的scope-resolver属性以及实现ScopeMetadataResolver接口。
代码
<?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:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd"> <context:component-scan base-package="com.daks.*" scope-resolver="com.daks.action.MyScopeResolver"/> </beans>
package com.daks.action;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.ScopeMetadata;
import org.springframework.context.annotation.ScopeMetadataResolver;
import org.springframework.context.annotation.ScopedProxyMode;
/**
*
* @author Alan
*/
public class MyScopeResolver implements ScopeMetadataResolver {
@Override
public ScopeMetadata resolveScopeMetadata(BeanDefinition definition) {
ScopeMetadata result = new ScopeMetadata();
result.setScopedProxyMode(ScopedProxyMode.NO);
result.setScopeName("prototype");
return result;
}
}