修改Spring默认的单例模式

背景

在我们的项目中,通过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;
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值