发布于2021-03-13 14:26 阅读(1012) 评论(0) 点赞(21) 收藏(3)
Spring 实现自定义的 bean 作用域
以下实现一个线程级别的 bean 的作用域
先看 Scope 接口的实现
- /**
- * 线程级别 scope
- *
- * @author ConstXiong
- */
- public class ThreadLocalScope implements Scope {
-
- public static final String SCOPE_NAME = "thread-local";
-
- private static final ThreadLocal<Map<String, Object>> THREAD_LOCAL = new ThreadLocal<Map<String, Object>>() {
- @Override
- protected Map<String, Object> initialValue() {
- return new HashMap<>();
- }
- };
-
- @Override
- public Object get(String name, ObjectFactory<?> objectFactory) {
- Map<String, Object> map = THREAD_LOCAL.get();
- Object object = map.get(name);
- if (object == null) {
- object = objectFactory.getObject();
- map.put(name, object);
- }
- return object;
- }
-
- @Override
- public Object remove(String name) {
- return THREAD_LOCAL.get().remove(name);
- }
-
- @Override
- public void registerDestructionCallback(String name, Runnable callback) {
- }
-
- @Override
- public Object resolveContextualObject(String key) {
- return THREAD_LOCAL.get().remove(key);
- }
-
- @Override
- public String getConversationId() {
- return String.valueOf(Thread.currentThread().getId());
- }
-
- }
使用 ApplicationContextAware 接口获取 ApplicationContext,在其 BeanFactory 中注册 ThreadLocalScope
- /**
- * 注册 ThreadLocalScope
- *
- * @author ConstXiong
- */
- @Component
- public class ScopeRegister implements ApplicationContextAware {
-
- @Override
- public void setApplicationContext(ApplicationContext applicationContext)
- throws BeansException {
- WebApplicationContext context = (WebApplicationContext)applicationContext;
- DefaultListableBeanFactory beanFactory = ((DefaultListableBeanFactory)context.getAutowireCapableBeanFactory());
- beanFactory.registerScope(ThreadLocalScope.SCOPE_NAME, new ThreadLocalScope());
- }
-
- }
bean 配置与 controller
- /**
- * controller
- *
- * @author ConstXiong
- */
- @Controller
- public class IndexController {
-
- @Autowired
- private ApplicationContext context;
-
- @RequestMapping("thread")
- @ResponseBody
- public String thread() {
- User user = context.getBean("user", User.class);
- return String.format("thread:%s, user:%s", Thread.currentThread().getId(), user);
- }
-
- @Bean
- @Scope(ThreadLocalScope.SCOPE_NAME)
- private static User user() {
- return new User();
- }
-
- }
这样在页面请求 http://localhost:8080/thread,线程 id 不同,bean id 也不同
完整代码:023-spring-bean-custom-scope
原文链接:https://blog.csdn.net/meism5/article/details/114685782
作者:飞翔公园
链接:http://www.javaheidong.com/blog/article/114246/5279cfa6837a6e119ea7/
来源:java黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 java黑洞网 All Rights Reserved 版权所有,并保留所有权利。京ICP备18063182号-2
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!