網站首頁 編程語言 正文
一、說明
SmartInitializingSingleton 接口的 afterSingletonsInstantiated()方法類似bean實例化執行后的回調函數。
afterSingletonsInstantiated 會在spring 容器基本啟動完成后執行。此時所有的單列bean都已初始化完成。實現了SmartInitializingSingleton 接口的類
可以在afterSingletonsInstantiated 中做一些回調操作。
二、XXL-JOB 中SmartInitializingSingleton 的使用
xxl-job 是一個輕量級的分布式任務調度框架,通過一個中心式的調度平臺,調度多個執行器執行任務,而且監控界面就集成在調度中心,界面又簡潔。
xxl-job中, XxlJobSpringExecutor,XxlJobSimpleExecutor 繼承自 XxlJobExecutor 同時也實現了 SmartInitializingSingleton 接口。
XxlJobSpringExecutor 在 afterSingletonsInstantiated() 方法中,完成了提取 @XxlJob 注解標注的方法,用于后續任務的執行。調用父類方法中的start() 方法,初始化netty服務器。
public class XxlJobSpringExecutor extends XxlJobExecutor implements ApplicationContextAware, SmartInitializingSingleton, DisposableBean {
private static final Logger logger = LoggerFactory.getLogger(XxlJobSpringExecutor.class);
// start
@Override
public void afterSingletonsInstantiated() {
// init JobHandler Repository
/*initJobHandlerRepository(applicationContext);*/
// init JobHandler Repository (for method)
initJobHandlerMethodRepository(applicationContext);
// refresh GlueFactory
GlueFactory.refreshInstance(1);
// super start
try {
super.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/// 其他代碼 省略
}
父類中的start() 方法:initEmbedServer 用于初始化netty服務。
// ---------------------- start + stop ----------------------
public void start() throws Exception {
// init logpath
XxlJobFileAppender.initLogPath(logPath);
// init invoker, admin-client
initAdminBizList(adminAddresses, accessToken);
// init JobLogFileCleanThread
JobLogFileCleanThread.getInstance().start(logRetentionDays);
// init TriggerCallbackThread
TriggerCallbackThread.getInstance().start();
// init executor-server 初始化netty 服務
initEmbedServer(address, ip, port, appname, accessToken);
}
獲取容器中被@XxlJob 注解標注的方法的實現方法:
private void initJobHandlerMethodRepository(ApplicationContext applicationContext) {
if (applicationContext == null) {
return;
}
// init job handler from method
String[] beanDefinitionNames = applicationContext.getBeanNamesForType(Object.class, false, true);
for (String beanDefinitionName : beanDefinitionNames) {
Object bean = applicationContext.getBean(beanDefinitionName);
Map<Method, XxlJob> annotatedMethods = null; // referred to :org.springframework.context.event.EventListenerMethodProcessor.processBean
try {
annotatedMethods = MethodIntrospector.selectMethods(bean.getClass(),
new MethodIntrospector.MetadataLookup<XxlJob>() {
@Override
public XxlJob inspect(Method method) {
return AnnotatedElementUtils.findMergedAnnotation(method, XxlJob.class);
}
});
} catch (Throwable ex) {
logger.error("xxl-job method-jobhandler resolve error for bean[" + beanDefinitionName + "].", ex);
}
if (annotatedMethods==null || annotatedMethods.isEmpty()) {
continue;
}
for (Map.Entry<Method, XxlJob> methodXxlJobEntry : annotatedMethods.entrySet()) {
Method executeMethod = methodXxlJobEntry.getKey();
XxlJob xxlJob = methodXxlJobEntry.getValue();
// regist
registJobHandler(xxlJob, bean, executeMethod);
}
}
}
使用時和其他框架差不多,在@Configuraton 修飾的配置類中返回一個示例化的bean即可。
@Configuration
public class XxlJobConfig {
@Bean
public XxlJobSpringExecutor xxlJobExecutor() {
logger.info(">>>>>>>>>>> xxl-job config init.");
XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor();
xxlJobSpringExecutor.setAdminAddresses(adminAddresses);
xxlJobSpringExecutor.setAppname(appname);
xxlJobSpringExecutor.setAddress(address);
xxlJobSpringExecutor.setIp(ip);
xxlJobSpringExecutor.setPort(port);
xxlJobSpringExecutor.setAccessToken(accessToken);
xxlJobSpringExecutor.setLogPath(logPath);
xxlJobSpringExecutor.setLogRetentionDays(logRetentionDays);
return xxlJobSpringExecutor;
}
}
三、spring 容器中 SmartInitializingSingleton 的使用
EventListenerMethodProcessor也實現了 SmartInitializingSingleton 接口,主要用于完成@EventListener注解方式的事件監聽。
在afterSingletonsInstantiated() 方法中處理邏輯與xxl-job 中的類似,都是用于篩選實例中被指定注解修飾的方法。
public class EventListenerMethodProcessor
implements SmartInitializingSingleton, ApplicationContextAware, BeanFactoryPostProcessor {
@Override
public void afterSingletonsInstantiated() {
ConfigurableListableBeanFactory beanFactory = this.beanFactory;
Assert.state(this.beanFactory != null, "No ConfigurableListableBeanFactory set");
String[] beanNames = beanFactory.getBeanNamesForType(Object.class);
for (String beanName : beanNames) {
if (!ScopedProxyUtils.isScopedTarget(beanName)) {
Class<?> type = null;
try {
type = AutoProxyUtils.determineTargetClass(beanFactory, beanName);
}
catch (Throwable ex) {
// An unresolvable bean type, probably from a lazy bean - let's ignore it.
if (logger.isDebugEnabled()) {
logger.debug("Could not resolve target class for bean with name '" + beanName + "'", ex);
}
}
if (type != null) {
if (ScopedObject.class.isAssignableFrom(type)) {
try {
Class<?> targetClass = AutoProxyUtils.determineTargetClass(
beanFactory, ScopedProxyUtils.getTargetBeanName(beanName));
if (targetClass != null) {
type = targetClass;
}
}
catch (Throwable ex) {
// An invalid scoped proxy arrangement - let's ignore it.
if (logger.isDebugEnabled()) {
logger.debug("Could not resolve target bean for scoped proxy '" + beanName + "'", ex);
}
}
}
try {
processBean(beanName, type);
}
catch (Throwable ex) {
throw new BeanInitializationException("Failed to process @EventListener " +
"annotation on bean with name '" + beanName + "'", ex);
}
}
}
}
}
}
寫在最后
以上兩個使用的方式都是在spring容器 單列被加載完成后,處理一些自定義的邏輯。EventListenerMethodProcessor主要用于篩選出被@EventListener
注解的方法,在后續的使用中 通過 發布-訂閱模式,實現事件的監聽。
XxlJobSpringExecutor 主要用于篩選出被@XxlJob 注解標注的方法,用于后續任務的啟動和停止。
原文鏈接:https://blog.csdn.net/daxues_/article/details/125750267
相關推薦
- 2022-05-17 ubuntu E: 無法獲得鎖 /var/lib/dpkg/lock-frontend - open
- 2022-08-06 Qt實現簡單折線圖表_C 語言
- 2023-05-15 Go語言實現AES加密并編寫一個命令行應用程序_Golang
- 2022-04-14 Python實現注冊登錄功能_python
- 2022-11-02 Python+eval函數實現動態地計算數學表達式詳解_python
- 2022-08-17 R語言ggplot2拼圖包patchwork安裝使用_R語言
- 2023-07-05 uni-app滾動分頁 兼容(App 小程序 H5)
- 2022-03-15 Spring Boot 是如何控制版本和自動配置的
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支