组件扫描

Time: 2024-05-15 Wednesday 12:21:01
Author: Jackasher

组件扫描

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package org.example.client;

import org.example.annoation.Component;

import java.io.File;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;

public class ComponentScan {
public static void main(String[] args) {
HashMap<String, Object> beanMap = new HashMap<>();
String packageName = "org.example.pojo";
String packagePath = packageName.replaceAll("\\.", "/");
System.out.println(packagePath);
URL url = ClassLoader.getSystemClassLoader().getResource(packagePath);
String path = url.getPath();
System.out.println(path);
File file = new File(path);
File[] files = file.listFiles();
Arrays.stream(files).forEach(f ->{

try {
System.out.println(f.getName().split("\\.")[0]);
String className = packageName + "." + f.getName().split("\\.")[0];
Class<?> aClass = Class.forName(className);
if (aClass.isAnnotationPresent(Component.class)) {
Component annotation = aClass.getAnnotation(Component.class);
String id = annotation.value();
Object o = aClass.newInstance();
beanMap.put(id,o);

}
} catch (Exception e) {
throw new RuntimeException(e);
}


});

System.out.println(beanMap);
}
}


组件扫描
http://example.com/2024/05/15/组件扫描/
作者
Jack Asher
发布于
2024年5月15日
许可协议