利用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文件当中添加网络权限: < ...
随机推荐
- (转)WEB页面导出为Word文档后分页&横向打印的方法
<html> <HEAD> <title>WEB页面导出为Word文档后分页&横向打印的方法 </title> < ...
- 给定制的vuejs组件添加v-model双向绑定支持
用过vuejs的前端工程师,对于v-model一定印象深刻.它向类似textarea,input等原生html原生添加双向数据绑定的能力非常方便.但是对于你的定制vue组件并不是能够直接应用v-mod ...
- crawler_app_在Airtest无线模式控制手机
无线模式开启: adb tcpip 48887 参考引用: https://www.cnblogs.com/xieqiankun/p/wireless-mode-of-poco.html
- TinyMCE基础配置
选择器配置 插件配置 工具栏配置 菜单配置 皮肤配置 编辑区宽高配置 编辑区样式配置 隐藏状态栏 选择器配置 选择器就是CSS选择器,它告诉TinyMCE哪个元素是可编辑的. 示例: tinymce. ...
- QGraphicsItem鼠标旋转控制研究
在QT场景视图中2D图形项Item的基类为QGraphicsItem,如果我们需要自定义Item则可以从其派生,然后重写boundingRect以及paint虚函数实现图形项的外边界定义以及内容绘制工 ...
- Android 培训准备资料之project与module的区别(1)
project和module的区别? 现在我们来看看在Android studio中怎样新建一个project (1)file->new->new project. Application ...
- iperf3 网络测试工具
Iperf3 是一个网络性能测试工具.Iperf可以测试最大TCP和UDP带宽性能,具有多种参数和UDP特性,可以根据需要调整,可以报告带宽.延迟抖动和数据包丢失.对于每个测试,它都会报告带宽,丢包和 ...
- itextpdf使用中文字体的三种方式
使用itextpdf时,默认的字体没有中文,总结了一下使用中文字体的方式. 1.使用windows系统下的字体,该种方式的具体操作可以看另一篇博客:https://www.cnblogs.com/wh ...
- 网络编程(四)--基于udp协议的套接字、socketserver模块
一.UDP协议(数据报协议) 1.何为udp协议 不可靠传输,”报头”部分一共只有8个字节,总长度不超过65,535字节,正好放进一个IP数据包. 以太网头 ip头 ...
- Elasticsearch高版本安装head插件
安装Elasticsearch 1.安装Elasticsearch-6.5.4.tar.gz [merce@info5 ~]$ cd /appmerce/zrapp/ [merce@info5 zra ...