自定义scope创建实例源码:
注册自定义的scope:使用BeanDefinitionRegistryPostProcessor接口:
package com.spring.postProcessor;
import com.spring.bean.ScopeDemo;
import org.springframework.beans.BeansException;
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 RefreshBeanDefinitionRegistryPostProsser implements BeanDefinitionRegistryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
//将自定义的scope注册到spring的scopes容器中
beanFactory.registerScope("refreshScope",new ScopeDemo());
}
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
}
}
自定义的scope:必须实现Scope接口
package com.spring.bean;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;
import java.lang.annotation.Annotation;
public class ScopeDemo implements Scope {
@Override
public Object get(String name, ObjectFactory> objectFactory) {
Object object = objectFactory.getObject();
return object;
}
@Override
public Object remove(String name) {
return null;
}
@Override
public void registerDestructionCallback(String name, Runnable callback) {
}
@Override
public Object resolveContextualObject(String key) {
return null;
}
@Override
public String getConversationId() {
return null;
}
}
应用:
package com.spring.bean;
import lombok.Data;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Data
@Scope("refreshScope")//scope的名称,默认single
public class CustomScopeTest {
private String test;
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)