自定义实现Spring Scope扩展
本文简单介绍实现Scope扩展的方法,其实很简单只要实现Scope接口,并通过beanfactory的registerScope将自定义scope 注册到Spring容器。
Spring Scope
Scope | 描述 |
---|
singleton | 默认spring 容器管理的bean 都是单例 | prototype | 定义任意数量的对象实例 | request | 只有web容器才有,一个http 请求对应一个对象实例 | session | 只有web容器才有,每一个http session 对应一个对象实例. | application | 只有web容器才有, ServletContext 对应个对象实例. | websocket | 只有web容器才有,将单个 Bean 定义的范围限定为 WebSocket 的生命周期 |
自定义TenantScope --实现Scope 类
public class TenantScope implements Scope {
private Map<String, Object> scopedObjects = Collections.synchronizedMap(new HashMap<String, Object>());
private Map<String, Runnable> destructionCallbacks = Collections.synchronizedMap(new HashMap<String, Runnable>());
@Override
public Object get(String name, ObjectFactory<?> objectFactory) {
if (!scopedObjects.containsKey(name)) {
scopedObjects.put(name, objectFactory.getObject());
}
return scopedObjects.get(name);
}
@Override
public Object remove(String name) {
destructionCallbacks.remove(name);
return scopedObjects.remove(name);
}
@Override
public void registerDestructionCallback(String name, Runnable callback) {
destructionCallbacks.put(name, callback);
}
@Override
public Object resolveContextualObject(String key) {
return null;
}
@Override
public String getConversationId() {
return "tenant";
}
}
实现注册到容器
public class TenantBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory factory) throws BeansException {
factory.registerScope("tenant", new TenantScope());
}
}
编写测试demo
public class TenantBean {
private final String name;
public TenantBean(String name) {
this.name = name;
}
public void pringName() {
System.out.println(String.format("Tenant from %s of type %s", this.name, this.getClass().getName()));
}
}
- 配置TenantBeanFactoryPostProcessor
@Configuration
public class TenantScopeConfig {
@Bean
public static BeanFactoryPostProcessor beanFactoryPostProcessor() {
return new TenantBeanFactoryPostProcessor();
}
}
@Configuration
public class TenantBeansConfig {
@Scope(scopeName = "tenant")
@Bean
public TenantBean foo() {
return new TenantBean("foo");
}
@Scope(scopeName = "tenant")
@Bean
public TenantBean bar() {
return new TenantBean("bar");
}
}
- 运行springboot 项目,并获取TenantBean对应实例化的两个bean,并调用printName方法
@SpringBootApplication
public class SpringbootScopeDemoApplication {
public static void main(String[] args) {
ConfigurableApplicationContext ctx= SpringApplication.run(SpringbootScopeDemoApplication .class, args);
TenantBean foo = (TenantBean) ctx.getBean("foo", TenantBean.class);
foo.pringName();
TenantBean bar = (TenantBean) ctx.getBean("bar", TenantBean.class);
bar.pringName();
}
}
|