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

实现简单的Springboot自动加载机制

一、文件目录

二、代码

2.1 注解类

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyComponent {
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface MyComponentScan {
}

2.2 实体类

@MyComponent
public class Person {private String name;public String getName() {return this.name;}public void setName(String name) {this.name = name;}@Overridepublic String toString() {return "[person]: name:" + this.name;}}

2.3 自动加载代码

@MyComponentScan
public class MySpringBoot {public static final Map<Class<?>, Object> BeanMap = new HashMap<>();public static void main(String[] args) {Class<MySpringBoot> mySpringBootClass = MySpringBoot.class;MyComponentScan annotation = mySpringBootClass.getAnnotation(MyComponentScan.class);if (annotation != null) {File file = new File(MySpringBoot.class.getResource(".").getPath());if (!file.exists()) {System.out.println("文件不存在");return;}getBean(file);}System.out.println(getBean(Person.class));}public static void getBean(File file) {for (File subFile : file.listFiles()) {if (subFile.isDirectory()) {getBean(subFile);} else {if (subFile.getName().endsWith("class")) {String absolutePath = subFile.getAbsolutePath();String classPath = absolutePath.split("classes" + File.separatorChar)[1];String className = classPath.substring(0, classPath.length() - 6).replace(File.separatorChar, '.');try {Class<?> clazz = Class.forName(className);MyComponent annotation = clazz.getAnnotation(MyComponent.class);if (annotation != null) {Object object = clazz.getConstructor().newInstance();BeanMap.put(clazz, object);}} catch (ClassNotFoundException | InvocationTargetException | InstantiationException | IllegalAccessException | NoSuchMethodException e) {throw new RuntimeException(e);}}}}}public static <T> T getBean(Class<T> clazz) {Object bean = BeanMap.get(clazz);if (bean == null) {return null;}return (T) bean;}}

三、输出结果

http://www.dtcms.com/a/606447.html

相关文章:

  • 人群计数的课程学习——是否值得:
  • 品牌网站建设报价表wordpress china
  • eyoucms 如何采集文章呢?基于php的采集样例
  • 重庆网站建设与网络推广动漫设计专业需要学什么
  • 微信小程序uniapp开发附源码——图片加水印
  • 高端 网站定制建站网址怎么改
  • 生物素-羟脯氨酸,biotin-羟脯氨酸 ,Biotin-Hyp,生物应用
  • Rust 并发实战:使用 Tokio 构建高性能异步 TCP 聊天室
  • 网站权重最高是多少怎样做网站的优化排名
  • 深圳阿赛姆电子|4GWIFI芯片浪涌整改案例
  • Python OpenCV图像识别在教育管理中的应用研究
  • 别人帮自己做网站有后门吗延吉市建设局网站
  • okhttp详解
  • 云防火墙如何实现多层网络防护
  • 智能家居为什么推荐使用UWB,UWB能够实现什么功能?
  • 海尔网站的建设特点自建网站餐饮服务提供者应在通信主管部门备案后
  • 不会被封的网站谁做免费空间有哪些
  • 30.计算云服务
  • AI赋能的$AIOT:打造Web3全周期智能生态的价值核心
  • 【算法】定义和类别
  • 如东网站建设lnmp wordpress 安装
  • 【C++】AVL 树
  • c++之基础A(无返回函数)第三课
  • 温州网站建设温州网站制作百度禁止seo推广
  • 南宁市网站开发公司电话wordpress wp-login
  • 合肥制作手机网站中国供求网
  • Nine.fun|从极致用户体验到社区自治的价值闭环
  • 淘宝客做的最好的网站怎么弄一个网站平台
  • 华为OD机试 双机位A卷 - 项目排期 / 最少交付时间 (JAVA Python C++ JS GO)
  • websocket操作入门