栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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;


public class ThreadSpringScope implements Scope {
    private static final Log logger = LogFactory.getLog(ThreadSpringScope.class);

    private final ThreadLocal> threadScope = ThreadLocal.withInitial(HashMap::new);

    
    @Override
    public Object get(String beanName, ObjectFactory objectFactory) {
        Map 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;


@Component
public class ThreadScopeRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {

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

  
  @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;


@Slf4j
@Component
@Scope("thread")
public class SpringCustomScope {

    private final Map 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值}=================
 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/931182.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号