编写一个maven插件,install到本地仓库,其他项目通过引用这个插件来统计文件的数量
准备一个编写插件的类
引入相关的依赖,并将改pom的打包方式改成
<!--自定义插件所需依赖-->
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-plugin-api</artifactId>
<version>3.5.0</version>
</dependency>
<dependency>
<groupId>org.apache.maven.plugin-tools</groupId>
<artifactId>maven-plugin-annotations</artifactId>
<version>3.5</version>
<scope>provided</scope>
</dependency>
<packaging>maven-plugin</packaging>
自定义一个CustomizeMojo 继承 AbstractMojo类,并实现其execute()方法
/**
* @author evan_qb
* @version 1.0
* @date 2019/4/30 16:11
*/
@Mojo(name = "customizeEdu",defaultPhase = LifecyclePhase.PACKAGE)
@Slf4j
public class CustomizeMojo extends AbstractMojo {
private static List<String> fileList = new ArrayList<>();
private static int allLines = 0;
@Parameter(property = "currentBaseDir",defaultValue = "User/pathHome")
private String currentBaseDir;
@Parameter(property = "suffix",defaultValue = ".java")
private String suffix;
@Override
public void execute() throws MojoExecutionException, MojoFailureException{
fileList = scanFile(currentBaseDir);
log.info("文件路径:{}",currentBaseDir);
log.info("java文件数量:{}", CustomizeMojo.fileList.size());
log.info("java代码总行数:{}",allLines);
}
/**
* 统计文件数量,将符合条件的文件存入集合中
* @param filePath
* @return
*/
private List<String> scanFile(String filePath){
File dir = new File(filePath);
for (File file:dir.listFiles()){
if (file.isDirectory()){
scanFile(file.getAbsolutePath());
}else {
if (file.getName().endsWith(suffix)){
fileList.add(file.getName());
//后面加一是为了迎合编辑器
allLines += countLine(file) + 1;
}
}
}
return fileList;
}
/**
* 统计每个文件的行数
* @param file
* @return
*/
private int countLine(File file){
int lines = 0;
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(file));
while (br.ready()){
br.readLine();
lines++;
}
}catch (IOException e){
log.error("e:{}",e);
}finally {
try {
if (br != null){
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return lines;
}
}
此时一个插件就制作好了,我们使用install命令,安装到本地仓库
mvn clean install
接着我们另外定义一个项目对其进行使用,在新项目的pom中加入,传入需要扫描的目录、后缀名并将其挂载到maven的生命周期package上
<build>
<plugins>
<!--自定义插件-->
<plugin>
<groupId>cn.qblank</groupId>
<artifactId>customize-plugin</artifactId>
<version>1.0-SNAPSHOT</version>
<configuration>
<currentBaseDir>${basedir}\src\main\java</currentBaseDir>
<suffix>.java</suffix>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>customizeEdu</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
此时可以看到我们自定义的插件,我们可以直接运行,也可以在install或package时运行