Spring中如何自定义bean的scope作用域--线程

spring如何自定义一个bean的作用域呢?首先我们需要实现一个接口--Scope(有很多,注意实现的是org.springframework.beans.factory.config路径下的),然后重写接口的方法,总共有五个:get--从作用域返回实例、remove--从作用域删除实例、registerDestructionCallBack--注册销毁回调方法、resolveContextual--根据key获取上下文对象、getConversationId--获得当前scope会话ID;主要是重写get与remove方法。

        然后再通过实现BeanDefinitionRegistryPostProcessor接口,重写两个方法postProcessBeanFactory--此方法是BeanDefinitionResgistryPostProcessor的父类BeanFactoryPostProcessor中的方法,可以得到ConfigurableListableBeanFactory,在实例化bean之前,可以覆盖或添加属性、postProcessBeanDefinitionRegistry--对BeanDefintion进行管理,增删查;

        废话不多说了,开搞:

1.首先实现自己的scope:

        主要重写get和remove方法

package com.liu.spring;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;

import java.util.HashMap;
import java.util.Map;

/**
  * 自定义spring中bean的作用域--线程级别
  * @author kevin
  * @date 2022/5/22
  */
public class ThreadSpringScope implements Scope {
    private static final Log logger = LogFactory.getLog(ThreadSpringScope.class);

    private final ThreadLocal<Map<String, Object>> threadScope = ThreadLocal.withInitial(HashMap::new);

    /**
     * 返回当前作用域中name对应的bean对象
     * @param beanName:需要检索的bean的名称
     * @param objectFactory:如果name对应的bean在当前作用域中没有找到,那么可以调用这个ObjectFactory来创建这个对象
     * @return java.lang.Object
     **/
    @Override
    public Object get(String beanName, ObjectFactory objectFactory) {
        Map<String, Object> scope = threadScope.get();
        //computeIfAbsent() 方法对 hashMap 中指定 key 的值进行重新计算,如果不存在这个 key,则添加到 hashMap 中
        //如果 key 对应的 value 不存在,则使用获取 remappingFunction 重新计算后的值,并保存为该 key 的 value,否则返回 value
        //此处:对scope中指定的 beanName 的值进行重新计算,如果不存在这个 beanName,则通过工具获取一个新的bean实例,添加到 hashMap 中
        Object bean = scope.computeIfAbsent(beanName, key -> objectFactory.getObject());
        logger.info("当前线程threadLocal得到的bean:" + bean);
        return bean;
    }

    public Object remove(String name) {
        Object result = threadScope.get().remove(name);
        threadScope.remove();
        return result;
    }

    public String getConversationId() {
        return null;
    }

    public Object resolveContextualObject(String key) {
        return null;
    }

    public void registerDestructionCallback(String name, Runnable callback) {

        logger.warn("线程级的作用域不支持解析回调!");
    }
}

2.将自定义的scope注册到容器:

        主要重写postProcessBeanFactory方法

package com.liu.spring;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.stereotype.Component;

/**
  * 自定义作用域注册
  * @author kevin
  * @date 2022/5/22
  */
@Component
public class ThreadScopeRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {

  private static final Log logger = LogFactory.getLog(ThreadScopeRegistryPostProcessor.class);

  /**
    * 在初始化之后修改应用程序上下文的内部bean工厂。所有bean定义都已加载,实例化bean之前,可以覆盖或添加属性
    * @author kevin
    * @param beanFactory :
    * @date 2022/5/23 13:07
    */
  @Override
  public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {

    beanFactory.registerScope("thread", new ThreadSpringScope()) ;
  } 
  @Override 
  public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
    logger.info("自定义作用域注册,此处以对BeanDefinition进行管理!");
  } 
} 

3.使用:

        定义自己的bean的时候,使用自定义的scope;通过map的值可以验证查看不同线程实例化的bean是不是一个

package com.liu.spring;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
  * 自定义作用域使用--线程级别
  * @author kevin
  * @date 2022/5/23
  */
@Slf4j
@Component
@Scope("thread")
public class SpringCustomScope {

    private final Map<String, String> testMap = new HashMap<>();

    @PostConstruct
    private void initMap() {
        testMap.put("-1", "我的静态初始化map值");
    }

    public void setMap(String key, String value){
        testMap.put(key, value);
    }

    public SpringCustomScope(){

        log.info("==============创建SpringCustomScope的bean=================");
    }

    public void testCustomScope(){

        log.info("=============CustomScope的test,testMap的值为:{}=================", testMap);
    }
}

4. 测试验证:

package com.liu.spring;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

@Slf4j
public class Test {

    public static void main(String[] args){
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("com.liu.spring");
        //自定义作用域
        for (int i = 0; i < 2; i++) {
            String now = "" + i;
            new Thread(() -> {
                Thread.currentThread().setName("线程" + now);
                SpringCustomScope customScope = (SpringCustomScope) context.getBean("springCustomScope");
                customScope.setMap("" + now, "我的线程" + now + " 的值,创建的bean为:" + customScope.toString());
                customScope.testCustomScope();
            }).start();
        }
        context.close();
    }
}

5.打印的结果:

13:20:29.281 [main] INFO com.liu.spring.ThreadScopeRegistryPostProcessor - 自定义作用域注册,此处以对BeanDefinition进行管理!
13:20:29.284 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerProcessor'
13:20:29.290 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
13:20:29.292 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
13:20:29.294 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
13:20:29.338 [线程1] INFO com.liu.spring.SpringCustomScope - ==============创建SpringCustomScope的bean=================
13:20:29.338 [线程0] INFO com.liu.spring.SpringCustomScope - ==============创建SpringCustomScope的bean=================
13:20:29.339 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@68fb2c38, started on Mon May 23 13:20:29 CST 2022
13:20:29.343 [线程1] INFO com.liu.spring.ThreadSpringScope - 当前线程threadLocal得到的bean:com.liu.spring.SpringCustomScope@33515beb
13:20:29.343 [线程0] INFO com.liu.spring.ThreadSpringScope - 当前线程threadLocal得到的bean:com.liu.spring.SpringCustomScope@33cf501d
13:20:29.343 [线程1] INFO com.liu.spring.SpringCustomScope - =============CustomScope的test,testMap的值为:{1=我的线程1 的值,创建的bean为:com.liu.spring.SpringCustomScope@33515beb, -1=我的静态初始化map值}=================
13:20:29.343 [线程0] INFO com.liu.spring.SpringCustomScope - =============CustomScope的test,testMap的值为:{0=我的线程0 的值,创建的bean为:com.liu.spring.SpringCustomScope@33cf501d, -1=我的静态初始化map值}=================
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值