利用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文件当中添加网络权限: < ...
随机推荐
- eclipse自定义导入或者编写版本格式化 xml
1.自定义或者自己导入版本格式 window——preferences——java——Code style ——formatter(New 或者 import)
- 2019 苏州朗动java面试笔试题 (含面试题解析)
本人5年开发经验.18年年底开始跑路找工作,在互联网寒冬下成功拿到阿里巴巴.今日头条.苏州朗动等公司offer,岗位是Java后端开发,因为发展原因最终选择去了苏州朗动,入职一年时间了,也成为了面 ...
- java自适应响应式 企业网站源码 SSM 生成静态化 手机 平板 PC
java 企业网站源码 前后台都有 静态模版引擎, 代码生成器大大提高开发效率 系统介绍: 1.网站后台采用主流的 SSM 框架 jsp JSTL,网站后台采用freemaker静态化模版引擎生成ht ...
- 浅聊标签<include>和<viewStub>
在开发中我们往往会遇到这种情况,当一个布局文件比较复杂时,我们一个劲地往里面拖各种控件button,textView,imageView阿等等,等过了一段时间后,出现bug,自己都把自己搞懵比啦,特别 ...
- Android Xutils3 完全解析
1.先来认识一下xUtils3 1)xUtils3简介 xUtils是基于Afinal开发的目前功能比较完善的一个Android开源框架,最近又发布了xUtil3.0,在增加新功能的同时又提高了框架的 ...
- Mybatis 子查询
在查询数据库时,需要以查询结果为查询条件进行关联查询. 在mybatis中通过association标签和collection标签实现子查询. 1. collection(集合)和associatio ...
- Linux Firewalld 基础实例
本次是一个Firewalld的基础操作实例,利用Firewalld图形操作界面进行访问控制操作. 实验拓扑 需求分析 首先拓扑涉及到两个区域,这里使用work和public区域,分别做相应的规则. 1 ...
- 面向对象(三)--多态、封装、property装饰器
一.多态与多态性 1.什么是多态 多态指的是同一种类/事物的不同形态 class Animal: def speak(self): pass class People(Animal): def spe ...
- metrics-server 安装问题解决
参考: https://www.qikqiak.com/post/install-metrics-server/ git clone https://github.com/kubernetes- ...
- 深入理解Java封装、继承、多态
转载请注明原文地址:https://www.cnblogs.com/ygj0930/p/10830957.html 一:封装 将类的某些信息隐藏在类内部,不允许外部程序直接访问,而是通过该类提供的方法 ...