We can specify a name package when using spring, and spring can automatically scan all the components under the package. Through the spring source code, in fact, this feature is not difficult to achieve.
First, all of the resources (files) under Classpath can be ClassLoader loaded. We can call its getResources() method to load the file under the classpath:
publicgetResources(String name) throws IOException
This method returns an Enumeration object that URL holds all the resources under the path as an object name . If we pass a package path cn/fh ,:
ClassLoader cl = Thread. CurrentThread(). Getcontextclassloader();enumeration<url> URLs = cl. Getresources("CN/FH");while (URLs. hasMoreElements()) {URL u = URLs. Nextelement();System. out. println(u);System. out. println(U. Getprotocol());System. out. println(U. GetPath());}
The following output results are available:
file:/Users/whf/projects/exam/out/production/exam/cn/fh/file/Users/whf/projects/exam/out/production/exam/cn/fh/
This is cn/fh not the result of the jar package. If it is in a jar package, the following information is output:
jar: File:/users/whf/.m 2/repository/cn/fh/web-security/2.1 .1 /web-security-2.1 .1 .jar !/cn/fh/jarfile: / Users/whf/.m 2/repository/cn/fh/web-security/ 2.1 .1 /web-security-2.1 .1 .jar !/cn/fh/
Thus, we can draw the idea of scanning function:
1. Call ClassLoader#getResources() the method to get the returned URL collection
2. Traverse all URL objects.
3. If it is a file, it iterates through all the files in that directory through file I/O operations *.class , extracting the class name.
4. If it is a jar package, traverse the jar package through the jar package I/O operation to fetch all the files in the package *.class .
Based on the above ideas, we can write a PkgScanner class and provide the following methods of use:
=new PkgScanner("cn.fh.pkgscanner"); List<String>list= scanner.scan(); list.-> System.out.println(f));
Output:
cn.fh.pkgscanner.PathUtilscn.fh.pkgscanner.PkgScannercn.fh.pkgscanner.ResourceType
Complete implementation in Github:https://github.com/wanghongfei/pkg-scanner
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Implementation of the Java class automatic scanning function