位置: IT常识 - 正文

【Spring Boot】SpringBoot设计了哪些可拓展的机制?(spring boot s)

编辑:rootadmin
【Spring Boot】SpringBoot设计了哪些可拓展的机制? 文章目录前言SpringBoot核心源码拓展Initializer拓展监听器ApplicationListenerBeanFactory的后置处理器 & Bean的后置处理器AOP其他的拓展点前言 当我们引入注册中心的依赖,比如nacos的时候,当我们启动springboot,这个服务就会根据配置文件自动注册到注册中心中,这个动作是如何完成的? 注册中心使用了SpringBoot中的事件监听机制,在springboot初始化的时候完成服务注册SpringBoot核心源码public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) { ... this.primarySources = new LinkedHashSet(Arrays.asList(primarySources)); // Servlet this.webApplicationType = WebApplicationType.deduceFromClasspath(); this.bootstrapRegistryInitializers = new ArrayList(this.getSpringFactoriesInstances(BootstrapRegistryInitializer.class)); // 注意这里,Initializers this.setInitializers(this.getSpringFactoriesInstances(ApplicationContextInitializer.class)); // 注意这里 Listeners this.setListeners(this.getSpringFactoriesInstances(ApplicationListener.class)); this.mainApplicationClass = this.deduceMainApplicationClass(); }

推荐整理分享【Spring Boot】SpringBoot设计了哪些可拓展的机制?(spring boot s),希望有所帮助,仅作参考,欢迎阅读内容。

文章相关热门搜索词:spring boot poi,spring boot 揭秘,spring boot s,spring spring boot,spring-boot-actuator,spring boot+ssm,spring spring boot,spring boot spi,内容如对您有帮助,希望把文章链接给更多的朋友!

我们可以看到空的SpringBoot项目有一些initializers以及一些listeners

注意这两行,换言之我们只要实现这两个类就可以自定义拓展SpringBoot了!

这里和手写Starter都是对SpringBoot的拓展,有兴趣的小伙伴可以看这篇文章

拓展Initializer

再看这张图

我们需要研究一下ApplicationContextInitializer这个类:

@FunctionalInterfacepublic interface ApplicationContextInitializer<C extends ConfigurableApplicationContext> { /** * Initialize the given application context. * @param applicationContext the application to configure */ void initialize(C applicationContext); }

这样就很清晰了,我们尝试手写一个继承类:

public class DemoInitializer implements ApplicationContextInitializer { @Override public void initialize(ConfigurableApplicationContext applicationContext) { System.out.println("自定义初始化器执行..."); ConfigurableEnvironment environment = applicationContext.getEnvironment(); Map<String, Object> map = new HashMap<>(1); map.put("name", "sccccc"); environment.getPropertySources().addLast(new MapPropertySource("DemoInitializer", map)); System.out.println("DemoInitializer execute, and add some property"); } }

通过SPI机制将自定义初始化器交给list集合initializers

然后再debug,就会发现:

【Spring Boot】SpringBoot设计了哪些可拓展的机制?(spring boot s)

最后经过一次回调:

private void prepareContext(DefaultBootstrapContext bootstrapContext, ConfigurableApplicationContext context, ... applyInitializers(context); ... // Add boot specific singleton beans 下面是beanFactory的操作

遍历所有的初始化器,然后

/*** Apply any {@link ApplicationContextInitializer}s to the context before it is * refreshed. * @param context the configured ApplicationContext (not refreshed yet) * @see ConfigurableApplicationContext#refresh() */ @SuppressWarnings({ "rawtypes", "unchecked" }) protected void applyInitializers(ConfigurableApplicationContext context) { for (ApplicationContextInitializer initializer : getInitializers()) { Class<?> requiredType = GenericTypeResolver.resolveTypeArgument(initializer.getClass(), ApplicationContextInitializer.class); Assert.isInstanceOf(requiredType, context, "Unable to call initializer."); initializer.initialize(context); } }

流程:

拓展监听器ApplicationListener

@FunctionalInterfacepublic interface ApplicationListener<E extends ApplicationEvent> extends EventListener { /** * Handle an application event. */ void onApplicationEvent(E event); /** * Create a new {@code ApplicationListener} for the given payload consumer. */ static <T> ApplicationListener<PayloadApplicationEvent<T>> forPayload(Consumer<T> consumer) { return event -> consumer.accept(event.getPayload()); } }

这里和上面initializer一样,就不演示了

BeanFactory的后置处理器 & Bean的后置处理器

Spring Boot解析配置成BeanDefinition的操作在invokeBeanFactoryPostProcessors方法中 自定义BeanFactory的后置处理器:

@Componentpublic class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor { @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { Arrays.asList(beanFactory.getBeanDefinitionNames()) .forEach(beanDefinitionName -> System.out.println(beanDefinitionName)); System.out.println("BeanFactoryPostProcessor..."); }}

自定义Bean的后置处理器:

@Componentpublic class MyBeanPostProcessor implements BeanPostProcessor { @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if(beanName.equals("userController")){ System.out.println("找到了userController: "+bean); } return null; }}AOP

这个相信大家用的比较多,可以自定义切面:

@Aspect@Componentpublic class LogAspect {// 切入点 Pointcut 可以对Service服务做切面@Pointcut("execution(* com.example.service.*.*(..))")public void mypointcut(){}// 前置通知@Before(value = "mypointcut()")public void before(JoinPoint joinPoint){ System.out.println("[前置通知] 准备开始记录日志..."); System.out.println("[前置通知] 目标类是: "+joinPoint.getTarget()); System.out.println("[前置通知] 目标方法是: "+joinPoint.getSignature().getName());}// 后置通知@AfterReturning(value = "mypointcut()")public void afterReturning(JoinPoint joinPoint){ System.out.println("[后置通知] 记录日志完成..."); System.out.println("[后置通知] 目标类是: "+joinPoint.getTarget()); System.out.println("[后置通知] 目标方法是: "+joinPoint.getSignature().getName());}/*@Around(value = "mypointcut()")public void around(ProceedingJoinPoint joinPoint){ System.out.println("[环绕通知] 日志记录前的操作..."); try { joinPoint.proceed(); System.out.println("[环绕通知] 日志记录后的操作..."); System.out.println("[环绕通知] "+joinPoint.getTarget()); System.out.println("[环绕通知] "+joinPoint.getSignature().getName()); } catch (Throwable throwable) { System.out.println("[环绕通知] 发生异常的操作..."); throwable.printStackTrace(); }finally { ... }}其他的拓展点Banner

方法地址: printBanner(env)->bannerPrinter.print->SpringBootBanner#printBanner 可以在resource目录下建立banner.txt文件夹实现自定义Banner

Runners

流程:

自定义:

@Componentpublic class JackApplicationRunner implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception { System.out.println("JackApplicationRunner..."); }}
本文链接地址:https://www.jiuchutong.com/zhishi/300352.html 转载请保留说明!

上一篇:OpenAI GPT-3模型详解(gpt3 模型大小)

下一篇:浅谈DNS域名解析的过程(dns域名解析两种方式)

  • 增值税加计扣除是什么意思啊
  • 权责发生制根据产品的生产特点和管理要求结转成本
  • 机票的抵扣进项怎么抵扣
  • 公司注销之后股东还承担责任吗
  • 重新建账 和之前数据差的多
  • 固定资产加速折旧税收优惠政策
  • 所得税减免优惠明细表应分摊期间
  • 汽车保险费可以抵扣吗
  • 分期收款销售商品确认收入会计分录
  • 其他应收款余额在贷方,怎么填资产负债表
  • 营改增租金收入税率
  • 白条确认收款后还能分期吗
  • 产成品或自制半成品核算方法有哪些
  • 货款打了未收到发票但是公司倒闭了怎么办?
  • 收取的职工房租如何入账
  • 工伤保险费发票
  • 小规模纳税人申报纳税详细流程
  • 股权转让成本法和权益法
  • 费用,资产,成本,损失的区别
  • 中奖个人所得税多少起征收
  • 应收补贴款贷方余额
  • 买一赠一怎么确定真假
  • 合同到期退房子,租金退吗
  • 免征的税款每月几号申报
  • 继续教育专项附加扣除需要什么材料
  • 利息调整摊销额等于什么
  • 借款利息资本化条件
  • 生产企业销售给其他单位的生产工具
  • window11 正式版
  • 土地增值税怎么计算举例说明
  • php curl_multi_init
  • Python之ImportError: DLL load failed: 找不到指定的模块解决方案
  • php输出流
  • php处理数组的函数
  • 【创作赢红包】ChatGPT引爆全网引发的AI算力思考
  • vue backbone
  • vue-cli2.0
  • tune a video:one-shot tuning of image diffusion models for text-to-video generation
  • excel2016添加指定行数
  • 给国外公司提供服务需要交哪些税
  • 向境外股东分配股息预提所得税
  • 企业应纳税所得额是指什么
  • 股权转让个人转个人要交什么税
  • 生产企业免抵退是什么意思
  • 固定资产入账原值含税价吗
  • sql server 2008简介
  • 免征增值税和增值税免税
  • 收据上面盖公章有用吗
  • 外包食堂如何进货
  • 周转材料怎么做分录
  • 子公司注销母公司长投账务处理
  • 通信地址需要写什么
  • 新成立公司会计未来规划
  • freebsd联网
  • 删除windowsapp
  • 灵活设置成员
  • win7 系统设置
  • 安装fedora33
  • win8.1 蓝屏
  • win1020h2正式版
  • win7打不开网页,可以重装系统吗
  • 微软称十年内将淘汰程序员
  • onekey.exe是什么
  • win命令行杀死一个程序
  • 工商网银安装
  • [置顶]公主大人接下来是拷问时间31
  • javascript语言介绍
  • nodejs搭建本地服务器运行html
  • mono为什么不能用了
  • unity资源包管理器
  • 浅谈python
  • jQuery easyui的validatebox校验规则扩展及easyui校验框validatebox用法
  • shell脚本启动应用程序
  • python字典有什么用
  • 基于mvc的项目实例
  • unity旋转角度范围限制
  • Android ImageLoader 本地缓存
  • 税务副科级选拔
  • 无锡市高新区税务局张贤平
  • 日本海淘推荐
  • 免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

    鄂ICP备2023003026号

    网站地图: 企业信息 工商信息 财税知识 网络常识 编程技术

    友情链接: 武汉网站建设