一、文件目录

二、代码
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;}}
三、输出结果
