“singleton” Bean & “prototype” Bean 作用域
prototype: Spring 容器没有办法管理 prototype Bean 的完整生命周期,也没有办法记录示例的存 在。销毁回调方法将不会执行
public class BeanScopeDemo implements DisposableBean {
@Bean
public static User singletonUser() {
return createUser();
}
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public static User prototypeUser() {
return createUser();
}
private static User createUser() {
User user = new User();
user.setId(System.nanoTime());
return user;
}
@Autowired
@Qualifier("singletonUser")
private User singletonUser;
@Autowired
@Qualifier("singletonUser")
private User singletonUser1;
@Autowired
@Qualifier("prototypeUser")
private User prototypeUser;
@Autowired
@Qualifier("prototypeUser")
private User prototypeUser1;
@Autowired
@Qualifier("prototypeUser")
private User prototypeUser2;
@Autowired
private Map<String, User> users;
@Autowired
private ConfigurableListableBeanFactory beanFactory;
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
applicationContext.register(BeanScopeDemo.class);
applicationContext.addBeanFactoryPostProcessor(beanFactory -> {
beanFactory.addBeanPostProcessor(new BeanPostProcessor() {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.printf("%s Bean 名称:%s 在初始化后回调...%n", bean.getClass().getName(), beanName);
return bean;
}
});
});
applicationContext.refresh();
scopedBeansByLookup(applicationContext);
scopedBeansByInjection(applicationContext);
applicationContext.close();
}
private static void scopedBeansByLookup(AnnotationConfigApplicationContext applicationContext) {
for (int i = 0; i < 3; i++) {
User singletonUser = applicationContext.getBean("singletonUser", User.class);
System.out.println("singletonUser = " + singletonUser);
User prototypeUser = applicationContext.getBean("prototypeUser", User.class);
System.out.println("prototypeUser = " + prototypeUser);
}
}
private static void scopedBeansByInjection(AnnotationConfigApplicationContext applicationContext) {
BeanScopeDemo beanScopeDemo = applicationContext.getBean(BeanScopeDemo.class);
System.out.println("beanScopeDemo.singletonUser = " + beanScopeDemo.singletonUser);
System.out.println("beanScopeDemo.singletonUser1 = " + beanScopeDemo.singletonUser1);
System.out.println("beanScopeDemo.prototypeUser = " + beanScopeDemo.prototypeUser);
System.out.println("beanScopeDemo.prototypeUser1 = " + beanScopeDemo.prototypeUser1);
System.out.println("beanScopeDemo.prototypeUser2 = " + beanScopeDemo.prototypeUser2);
System.out.println("beanScopeDemo.users = " + beanScopeDemo.users);
}
@Override
public void destroy() throws Exception {
System.out.println("当前 BeanScopeDemo Bean 正在销毁中...");
this.prototypeUser.destroy();
this.prototypeUser1.destroy();
this.prototypeUser1.destroy();
this.prototypeUser2.destroy();
for (Map.Entry<String, User> entry : this.users.entrySet()) {
String beanName = entry.getKey();
BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
if (beanDefinition.isPrototype()) {
User user = entry.getValue();
user.destroy();
}
}
System.out.println("当前 BeanScopeDemo Bean 销毁完成");
}
}
public class User implements BeanNameAware {
...
@Override
public void setBeanName(String name) {
this.beanName = name;
}
}
“request” Bean 作用域
servlet 容器相关每个 http 请求中创建一个新的实例; 采用动态代理,首先会创建一个代理对象,在每次 http 请求时代理对象内部会去创建一个新的目标对象实例 ? 配置
? XML - <bean class= "..." scope = "request" />
? Java 注解 - @RequestScope 或 @Scope(WebApplicationContext.SCOPE_REQUEST)
? 实现
? API - RequestScope
“session” Bean 作用域
servlet 容器相关,session 互斥, http 请求中创建一个新的实例; ? 配置
? XML - <bean class= "..." scope = "session" />
? Java 注解 - @RequestScope 或 @Scope(WebApplicationContext.SCOPE_REQUEST)
? 实现
? API - SessionScope
“application” Bean 作用域
servlet 容器相关,Bean 实例的生命周期和 ServletContext 一致; ? 配置
? XML - <bean class= "..." scope = "application" />
? Java 注解 - @ApplicationScope 或 @Scope(WebApplicationContext.SCOPE_APPLICATION)
? 实现
? API - ApplicationScope
自定义 Bean 作用域
? 实现 Scope
? org.springframework.beans.factory.config.Scope
? 注册 Scope
? API - org.springframework.beans.factory.config.ConfigurableBeanFactory#registerScope
? 配置
<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
<property name="scopes">
<map>
<entry key="...">
</entry>
</map>
</property>
</bean>
自定义线程级别作用域
同一个线程内是同一个实例,不同线程创建不同实例
public class ThreadLocalScope implements Scope {
public static final String SCOPE_NAME = "thread-local";
private final NamedThreadLocal<Map<String, Object>> threadLocal = new NamedThreadLocal("thread-local-scope") {
public Map<String, Object> initialValue() {
return new HashMap<>();
}
};
@Override
public Object get(String name, ObjectFactory<?> objectFactory) {
Map<String, Object> context = getContext();
Object object = context.get(name);
if (object == null) {
object = objectFactory.getObject();
context.put(name, object);
}
return object;
}
@NonNull
private Map<String, Object> getContext() {
return threadLocal.get();
}
@Override
public Object remove(String name) {
Map<String, Object> context = getContext();
return context.remove(name);
}
@Override
public void registerDestructionCallback(String name, Runnable callback) {
}
@Override
public Object resolveContextualObject(String key) {
Map<String, Object> context = getContext();
return context.get(key);
}
@Override
public String getConversationId() {
Thread thread = Thread.currentThread();
return String.valueOf(thread.getId());
}
}
public class ThreadLocalScopeDemo {
@Bean
@Scope(ThreadLocalScope.SCOPE_NAME)
public User user() {
return createUser();
}
private static User createUser() {
User user = new User();
user.setId(System.nanoTime());
return user;
}
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
applicationContext.register(ThreadLocalScopeDemo.class);
applicationContext.addBeanFactoryPostProcessor(beanFactory -> {
beanFactory.registerScope(ThreadLocalScope.SCOPE_NAME, new ThreadLocalScope());
});
applicationContext.refresh();
scopedBeansByLookup(applicationContext);
applicationContext.close();
}
private static void scopedBeansByLookup(AnnotationConfigApplicationContext applicationContext) {
for (int i = 0; i < 3; i++) {
Thread thread = new Thread(() -> {
User user = applicationContext.getBean("user", User.class);
System.out.printf("[Thread id :%d] user = %s%n", Thread.currentThread().getId(), user);
});
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private static void scopedBeansByInjection(AnnotationConfigApplicationContext applicationContext) {
}
}
Spring Cloud RefreshScope作用域实现动态刷新
原理类似
|