1.先构建注解:

    1. @Target(ElementType.TYPE)
    2. @Retention(RetentionPolicy.RUNTIME)
    3. public @interface Bean {
    4. String name() default "";
    5. }

    2.根据包名拿到路径下的class文件,同时在根据指定的注解去实例化

    1. public class SpringDemo {
    2. public static void main(String[] args)throws IOException {
    3. String packageName="com.springdemo";
    4. Map excuten = excuten(packageName);
    5. System.out.println(excuten);
    6. }
    7. /*由包名拿到class文件的全路径名*/
    8. public static String getpaths(String packageName){
    9. ClassLoader loader = SpringDemo.class.getClassLoader();
    10. URL resource = loader.getResource(packageName.toString().replace('.', '/'));
    11. String path = resource.getPath();
    12. File file = new File(path);
    13. String absolutePath = file.getAbsolutePath();
    14. return absolutePath;
    15. }
    16. /*字符串的截取,截取为包名的形式 */
    17. public static String packageName(Path path){
    18. String s1 = path.toString();
    19. int com = s1. lastIndexOf("com");
    20. int coms= s1.lastIndexOf(".class");
    21. String packageClassName = s1.substring(com, coms);
    22. String replace = packageClassName.replace('\\', '.');
    23. return replace;
    24. }
    25. //遍历文件目录那到class 文件,并通过反射拿到类中的注解类型。同时创建class 对象
    26. public static Map<String,? extends Object> excuten(String packageName) throws IOException {
    27. Map map = new HashMap<>();
    28. String getpaths = getpaths(packageName);
    29. Path path = Paths.get(getpaths);
    30. Files.walkFileTree(path, new SimpleFileVisitor<Path>(){
    31. @Override
    32. public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
    33. if(file.toString().endsWith(".class")){
    34. String packageName = packageName(file);//拿到包路径
    35. try {
    36. Class<?> aClass = Class.forName(packageName);
    37. Bean bean = aClass.getAnnotation(Bean.class);
    38. if (bean!=null){
    39. String name = bean.name();
    40. if (name.length()<1){
    41. name=aClass.getSimpleName();
    42. map.put(name,Class.forName(packageName).newInstance());
    43. }else{
    44. map.put(name,Class.forName(packageName).newInstance());
    45. }
    46. }
    47. }catch (Exception e){
    48. e.printStackTrace();
    49. }
    50. }
    51. return FileVisitResult.CONTINUE;
    52. }
    53. });
    54. return map;
    55. }
    56. }