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
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值}=================



