当前位置: 首页 > ai >正文

@Value注解底层原理(二)

        前面介绍了@Value注解的几种解析方式,下面可以是模拟@Value注解如何解析带有SPEL表达式的例子。

       测试类如下:

 public static void main(String[] args) throws NoSuchFieldException {AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestValue.class);ContextAnnotationAutowireCandidateResolver resolver = new ContextAnnotationAutowireCandidateResolver();resolver.setBeanFactory(context.getDefaultListableBeanFactory());extracted3(context,resolver,Bean4.class.getDeclaredField("value"));}

   解析的方法:

private static void extracted3(AnnotationConfigApplicationContext context, ContextAnnotationAutowireCandidateResolver resolver, Field field) {DependencyDescriptor descriptor = new DependencyDescriptor(field,true);//获取@Value的内容String value = resolver.getSuggestedValue(descriptor).toString();System.out.println(value);//解析${}value = context.getEnvironment().resolvePlaceholders(value);System.out.println(value);//解析#{}Object bean3 = context.getBeanFactory().getBeanExpressionResolver().evaluate(value, new BeanExpressionContext(context.getBeanFactory(), null));//类型转换Object res = context.getBeanFactory().getTypeConverter().convertIfNecessary(bean3, descriptor.getDependencyType());System.out.println(res);}

Bean4

    static class Bean4{@Value("#{'hello, '+'${JAVA_HOME}'}")private String value;}

测试结果:

       第一步是拿到@Value里面的整体内容,第二步解析里面带有${}的字符,第三步解析#{}里面的内容。下面的方法对SPEL表达式进行解析。

Object bean3 = context.getBeanFactory().getBeanExpressionResolver().evaluate(value, new BeanExpressionContext(context.getBeanFactory(), null));

       总结一下,无论是@Value注解还是@Autowired注解,其中用到的一些解析器都是类似的。获取属性上的注解然后根据类型不同进行层层处理。Spring底层提供了丰富的注解解析器。

http://www.xdnf.cn/news/19670.html

相关文章:

  • Redis 的整数集合:像分类收纳盒一样的整数专属存储
  • Obsidian本地笔记工具:构建知识网络关联笔记,支持Markdown与插件生态及知识图谱生成
  • LoRA至今历程回顾(74)
  • 《水浒智慧》第二部 “英雄是怎么炼成的” (上篇)读书笔记
  • Linux文本处理工具
  • 机器算法(五)模型选择与调优
  • 基于SpringBoot的广科大在线图书管理系统设计与实现(代码+数据库+LW)
  • 探索JavaScript机器学习:几款流行的库推荐
  • Leetcode 3670. Maximum Product of Two Integers With No Common Bits
  • HTML第四课:个人简介页面开发
  • 下载速度爆表,全平台通用,免费拿走!
  • DaemonSet Job CronJob 概念理解
  • XML在线格式化 - 加菲工具
  • Leetcode二分查找(3)
  • 移动硬盘删除东西后,没有释放空间
  • 【机器学习入门】5.2 回归的起源——从身高遗传到线性模型的百年演变
  • 狄利克雷分布作用
  • CentOS 创建站点
  • 二进制流进行预览pdf、excel、docx
  • Cisco FMC利用sftp Server拷贝文件方法
  • 0902 C++类的匿名对象
  • 面试问题:c++的内存管理方式,delete的使用,vector的resize和reverse,容量拓展
  • uni-app 布局之 Flex
  • 基于STM32与华为云联动的智能电动车充电桩管理系统
  • QSlider 和 QProgressBar 的区别与实践
  • 【Linux基础】Linux系统启动:深入解析Linux系统启动完整流程
  • 仿真波导中超短脉冲传输中的各种非线性效应所产生的超连续谱
  • AI如何理解PDF中的表格和图片?
  • qt安装FFmpeg后编译遇到error: collect2.exe: error: ld returned 1 exit status错误
  • 链表题类型注解解惑:理解Optional,理解ListNode