利用ApplicationListener和ContextRefreshedEvent加载自己的beanPool
基本原理:
1、Spring的ApplicationListener和ContextRefreshedEvent一般都是成对出现的。
2、在IOC的容器的启动过程中,当所有的bean都已经处理完成之后,spring ioc容器会有一个发布事件的动作。
3、当该发布事件的监听者监听到此动作时,ApplicationListener接口实例中的onApplicationEvent(E event)方法就会被调用。
4、调用该方法时,通过父类找到实现类,再根据业务场景(以下示例中为serviceID),将对应的bean填充至beanPool中。
5、这样,在编写业务代码时,直接通过serviceID就能找到对应处理的类
上代码
父类及各实现子类:
package com.test; /**
* @author zyydd
* @date 2019/12/9 10:37
*/
public abstract class TestServiceBase {
protected abstract String getServiceId(); public abstract void handle();
} package com.test; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service; /**
* @author zyydd
* @date 2019/12/9 10:36
*/
@Service
public class AtestService extends TestServiceBase {
private static final Logger logger = LoggerFactory.getLogger(AtestService.class); @Value("${testService.serviceId.aTest}")
private String serviceId; @Override
protected String getServiceId() {
return serviceId;
} @Override
public void handle() {
logger.info("hi everyOne, this is A!");
}
} package com.test; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service; /**
* @author zyydd
* @date 2019/12/9 10:36
*/
@Service
public class BtestService extends TestServiceBase {
private static final Logger logger = LoggerFactory.getLogger(BtestService.class); @Value("${testService.serviceId.bTest}")
private String serviceId; @Override
protected String getServiceId() {
return serviceId;
} @Override
public void handle() {
logger.info("hi everyOne, this is B!");
}
}
其中,serviceID是通过读取yaml中的配置,填充进去的,yaml配置:
testService:
serviceId:
aTest: 1001
bTest: 1002
自建的beanPool,系统启动时填充,业务流程中通过serviceID获取:
package com.test; import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils; import java.util.HashMap; /**
* @author zyydd
* @date 2019/12/9 10:42
*/
@Service
public class TestServicePool {
private HashMap<String, TestServiceBase> testServiceMap = new HashMap<>(16); public TestServiceBase get(String serviceId) {
return testServiceMap.get(serviceId);
} public void put(String serviceId, TestServiceBase testService) {
if (StringUtils.isEmpty(serviceId) || testService == null) {
return;
}
this.testServiceMap.put(serviceId, testService);
}
}
ApplicationListener接口实例,填充beanPool:
package com.test; import com.**.util.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils; import java.util.Map; /**
* @author zyydd
* @date 2019/12/9 10:46
*/
@Component
public class TestServiceLoadListener implements ApplicationListener<ContextRefreshedEvent> {
private static final Logger logger = LoggerFactory.getLogger(TestServiceLoadListener.class); @Autowired
private TestServicePool testServicePool; @Override
public void onApplicationEvent(ContextRefreshedEvent event) {
if (event.getApplicationContext().getParent() == null) {
logger.info("TestServiceLoadListener 开始加载");
//根据父类(TestServiceBase)加载子类bean
Map<String, TestServiceBase> beanMap = event.getApplicationContext().getBeansOfType(TestServiceBase.class);
logger.info("TestServiceLoadListener 加载结果={}", JsonUtils.toJSONString(beanMap));
//将子类挨个填充到testServicePool中
if (CollectionUtils.isEmpty(beanMap)) {
logger.error("TestServiceLoadListener 加载失败,无法获取TestServiceBase的子类!");
return;
} else {
for (TestServiceBase bean : beanMap.values()) {
testServicePool.put(bean.getServiceId(), bean);
logger.info("TestServiceLoadListener 加载一个: serviceid={} bean={}", bean.getServiceId(), bean.getClass().getName());
}
}
}
}
}
单元测试类:
package com.**.service; import com.**.web.Application;
import com.test.TestServiceBase;
import com.test.TestServicePool;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner; /**
* @author zyydd
* @date 2019/6/3 10:54
*/
@SpringBootTest(classes = Application.class)
@RunWith(SpringRunner.class)
public class TestServiceTest {
private static final Logger logger = LoggerFactory.getLogger(TestServiceTest.class); @Autowired
private TestServicePool testServicePool; @Test
public void testTestServicePool() {
TestServiceBase a = testServicePool.get("1001");
logger.info(a.getClass().getName());
a.handle();
} }
单元测试执行结果:
2019-12-09 11:12:26.100 INFO [main] com.test.TestServiceLoadListener [28] - TestServiceLoadListener 开始加载
2019-12-09 11:12:26.112 INFO [main] com.test.TestServiceLoadListener [31] - TestServiceLoadListener 加载结果={"atestService":{},"btestService":{}}
2019-12-09 11:12:26.113 INFO [main] com.test.TestServiceLoadListener [39] - TestServiceLoadListener 加载一个: serviceid=1001 bean=com.test.AtestService
2019-12-09 11:12:26.113 INFO [main] com.test.TestServiceLoadListener [39] - TestServiceLoadListener 加载一个: serviceid=1002 bean=com.test.BtestService 2019-12-09 11:12:27.067 INFO [main] com.**.service.TestServiceTest [30] - com.test.AtestService
2019-12-09 11:12:27.067 INFO [main] com.test.AtestService [26] - hi everyOne, this is A!
利用ApplicationListener和ContextRefreshedEvent加载自己的beanPool的更多相关文章
- 利用python进行数据加载和存储
1.文本文件 (1)pd.read_csv加载分隔符为逗号的数据:pd.read_table从文件.URL.文件型对象中加载带分隔符的数据.默认为制表符.(加载为DataFrame结构) 参数name ...
- WPF当属性值改变时利用PropertyChanged事件来加载动画
在我们的程序中,有时我们需要当绑定到UI界面上的属性值发生变化从而引起数据更新的时候能够加载一些动画,从而使数据更新的效果更佳绚丽,在我们的程序中尽量将动画作为一种资源放在xaml中,而不是在后台中通 ...
- 图片利用 new Image()预加载原理 和懒加载的实现原理
二:预加载和懒加载的区别 预加载与懒加载,我们经常经常用到,这些技术不仅仅限于图片加载,我们今天讨论的是图片加载: 图片预加载:顾名思义,图片预加载就是在网页全部加载之前,提前加载图片.当用户需要查看 ...
- 利用CAReplicatorLayer实现的加载动画
在上一篇中,笔者简要介绍了CAReplicatorLayer,在本篇中,将介绍具体的实用价值. 实用CAReplicatorLayer作为核心技术实现加载动画. 首先,创建一个UIView的子类 @i ...
- 利用LruCache为GridView加载大量本地图片完整示例
MainActivity如下: package cc.testlrucache; import android.os.Bundle; import android.widget.GridView; i ...
- 利用青瓷布局自定义加载的场景,而不是自己改写qici-loading
加载界面如果全部通过自己手动布局不仅不美观,还很难控制.借用原生的场景切换加载效果,来实现我们游戏的加载效果. 没有做加载修改的原来的加载顺序: 黑乎乎界面->(游戏定制的加载)你的第一个场 ...
- 利用css实现页面加载时旋转动画
有时浏览一些网站时在刚加载页面时候会出现一个滚动动画如下图,特别是对于一些移动端的站点或者混合应用来说应该用户体验会好很多,扒了下页面发现是用css样式控制的,于是把页面以及css样式赋值了下来, h ...
- C# DataGridVie利用model特性动态加载列
今天闲来无事看到ORm的特性映射sql语句.我就想到datagridview也可以用这个来动态添加列.这样就不用每次都去界面上点开界面填列了. 代码简漏希望有人看到了能指点一二. 先定义好Datagr ...
- Android框架Volley之:利用Imageloader和NetWorkImageView加载图片
首先我们在项目中导入这个框架: implementation 'com.mcxiaoke.volley:library:1.0.19' 在AndroidManifest文件当中添加网络权限: < ...
随机推荐
- Redis 实战搭建高可用架构
前言:最近在看关于redis缓存方面的知识,今天就来个 Redis sentinel 高可用架构,实战开始之前,先看看sentinel的概念 什么是redis-sentinel Redis-Senti ...
- 外网IP和内网IP区别
外网IP和内网IP区别? 网络结构 如图,假设我们的计算机现在就是设备一,我们想要访问百度.如果我们正使用着校园网,那么首先我们需要先通过校园网的路由器把我们的内网ip转为校园网的外网ip.然后通过这 ...
- 使用Vue CLI构建Vue项目
第一步:首先在控制台输入vue --version,如果出现版本号则进入第三步:否则进入第二步: 第二步:输入npm install cnpm -g --registry=https://regist ...
- C++中的Mat, const Mat, Mat &,Mat &, const Mat &的区别
Mat, copy传递,不会改变外部变量的Mat. Mat &, reference传递,函数内部修改将会改变外部. const Mat, copy传递,在函数内,不会被修改,也不会影响到外部 ...
- js内存空间
堆数据结构 堆数据结构是一种树状结构.它的存取数据的方式与书架和书非常相似.我们只需要知道书的名字就可以直接取出书了,并不需要把上面的书取出来.JSON格式的数据中,我们存储的key-value可以是 ...
- vue + yarn 创建项目
前期准备工作node,npm,vue,yarn等环境要准备好 1.命令行vue init webpack myproject 2.使用vs code打开项目文件夹, vs终端运行一下yarn 3.添加 ...
- web攻击日志分析之新手指
0x00 前言 现实中可能会经常出现web日志当中出现一些被攻击的迹象,比如针对你的一个站点的URL进行SQL注入测试等等,这时候需要你从日志当中分析到底是个什么情况,如果非常严重的话,可能需要调查取 ...
- Maven编译过程中出现的问题
在用Jenkins编译Gitlab上代码过程中,实际使用的是Maven服务器上的打包命令,以下为打包过程中出现的问题及解决方案 问题一:Maven无法编译Snapshot版本代码 答:登录至maven ...
- 三、python对字符串和集合的内存垃圾回收机制
变量声明: name1 = "andy" name2 = name1 这个时候我把name1的值给改成了“tom”,问现在name2的值是什么?为什么? 答:andy,因为你把 ...
- window开机启动
C:\Users\sunyues\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup 再次文件夹下写脚本就可 @echo off ...