java腦洞 效率工程利器-代碼解析maven插件 enum-export-plugin

前文介紹了核心組件: java腦洞 效率工程利器-代碼解析工具 lp-base-export

本文主要是介紹如何通過maven插件配合lp-base-export實現枚舉的解析

1. 先分享完整的demo :enum-export-plugin

第一步: 引入maven插件
<plugin>
                <groupId>io.github.wqr503</groupId>
                <artifactId>enum-export-plugin</artifactId>
                <version>1.3.0.FINAL</version>
                <configuration>
                    <taskList>
                        <task>
                            <id>enumTask</id>
                            <outPutDirection>${project.basedir}/export</outPutDirection>
                            <!--                            <classPaths>-->
                            <!--                                <classPath>${project.basedir}/target/classes</classPath>-->
                            <!--                            </classPaths>-->
                            <sourcePath>${project.basedir}/src/main/java</sourcePath>
                            <dependencyPaths>
                                <dependencyPath>${project.basedir}/target/lib</dependencyPath>
                            </dependencyPaths>
                            <logLevel>DEBUG</logLevel>
                            <logParam>true</logParam>
                            <mvlText>
                                <![CDATA[
public interface CombinationEnum {
@foreach{entity : entityList}
    // @{entity.typeName}
    String @{entity.name} = "@if{entity.desc != null}@{entity.desc} : @end{}@foreach{data : entity.valueList}@if{data.fieldList.size() > 0}@{data.fieldList[0].value}@end{}@if{data.fieldList.size() <= 0}@{data.ordinal}@end{}:@{data.name}(@if{data.desc != null}@{data.desc}@end{}),@end{}";
@end{}
}
  ]]>
                            </mvlText>
                        </task>
                    </taskList>
                </configuration>
            </plugin>
第二步: 啟用maven插件
image.png
第三步:查看輸出路徑
image.png

2. 手把手教你如何做插件

lp-export-maven-common項目(結合maven的通用向項目)

源碼地址: https://gitee.com/wqrzsy/lp-demo/tree/master/lp-export-maven-common
引入maven插件相關的包和lp-base-export包

        <dependency>
            <groupId>io.github.wqr503</groupId>
            <artifactId>lp-base-export</artifactId>
            <version>1.3.0.FINAL</version>
        </dependency>

        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-core</artifactId>
            <version>3.5.4</version>
        </dependency>

        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-plugin-api</artifactId>
            <version>3.5.4</version>
        </dependency>

        <dependency>
            <groupId>org.apache.maven.plugin-tools</groupId>
            <artifactId>maven-plugin-annotations</artifactId>
            <version>3.5.2</version>
        </dependency>

然后實現maven插件的入口AbstractMojo

//@Mojo()
public abstract class CommonMojo<T extends ExportTask> extends AbstractMojo {

    protected abstract List<T> getTaskList();

    protected abstract Process getProcess(T task);

    @Override
    public void execute() throws MojoExecutionException, MojoFailureException {
        MavenLocalLoggerFactory loggerFactory = new MavenLocalLoggerFactory(this);
        LogHandler.changeFactory(loggerFactory);
        for (T task : getTaskList()) {
            try {
                getLog().info("執行任務 : " + task.getId());
                Process process = getProcess(task);
                process.execute();
                getLog().info("執行任務 : " + task.getId() + " 完畢");
            } catch (Exception e) {
                getLog().error(task.getId() + " 任務執行失敗", e);
            }
        }
    }
}

這里注意到,為了實現多任務執行,我這里改造成列表形式

lp-export-maven-plugin項目(maven插件項目)

源碼地址:https://gitee.com/wqrzsy/lp-demo/tree/master/lp-export-maven-plugin
由于maven插件需要以pom形式打包,所以我們另起一個項目,然后pom文件如下

<dependencies>

        <dependency>
            <groupId>io.github.wqr503</groupId>
            <artifactId>lp-export-maven-common</artifactId>
            <version>1.3.0.FINAL</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>

<!--            添加maven-plugin-plugin插件依賴,這個包可以使插件支持JDK1.8以上的版本-->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-plugin-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <goalPrefix>lp</goalPrefix>
                    <skipErrorNoDescriptorsFound>true</skipErrorNoDescriptorsFound>
                </configuration>
            </plugin>

<!--            addDefaultImplementationEntries 會在生成的jar包的META-INF目錄下的MANIFEST.MF文件里生成版本信息-->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>3.3.0</version>
                <configuration>
                    <archive>
                        <manifest>
                            <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>

        </plugins>
    </build>
enum-export-plugin項目(具體實現項目,到這里就可以隨意按想象力發揮了)

源碼地址: https://gitee.com/wqrzsy/lp-demo/tree/master/enum-export-plugin
首先引入maven

    <parent>
        <groupId>io.github.wqr503</groupId>
        <artifactId>lp-export-maven-plugin</artifactId>
        <version>1.3.0.FINAL</version>
    </parent>

然后定義啟動名(插件列表看到的名字)

@Mojo(name = "enumExportAll")
public class EnumExport extends CommonMojo<CommonExportTask> {

    @Parameter
    private List<CommonExportTask> taskList;

    @Override
    protected List<CommonExportTask> getTaskList() {
        return taskList;
    }

    @Override
    protected Process getProcess(CommonExportTask commonExportTask) {
        getLog().info(JSONAide.toJson(commonExportTask));
        // 判斷是否聚合輸出
        if(commonExportTask.isCombination()) {
            return new EnumCombinationExportAll(commonExportTask);
        } else {
            return new EnumExportAll(commonExportTask);
        }
    }

}

具體實現

/** 聚合輸出plugin */
public class EnumCombinationExportAll extends CommonCombinationExportAllProcess {

    public EnumCombinationExportAll(CommonExportTask exportTask) {
        super(exportTask.getOutPutDirection(), exportTask.getSourcePath(), exportTask.getClassPaths(),
                exportTask.getBasePackages(), exportTask.getDependencyPaths(), exportTask.getMvlPath(),
                exportTask.getMvlText(), exportTask.isLogParam(), exportTask.getOutPutFileName(),
                exportTask.getLogLevel());
    }

    /** 顯示用途 */
    @Override
    public String getProcessName() {
        return "EnumCombinationExportAll";
    }

    /** 構建對象轉mvl的屬性 */
    @Override
    protected TableAttribute createTableAttribute() {
        return new TableAttribute() {

            private List<EnumEntity> entityList = new ArrayList<>();

            public void putAttribute(ScanClassInfo classInfo, TypeFormatter typeFormatter) {
                EnumEntity enumEntity = new EnumEntity();
                //從枚舉上提取類名
                enumEntity.setName(classInfo.getSimpleName());
                //從枚舉上提取描述
                enumEntity.setDesc(classInfo.getSourceClass().getDesc());
                //從枚舉上提取類名
                enumEntity.setTypeName(classInfo.getClassName());
                List<EnumValueEntity> valueList = new ArrayList<>();
                //從枚舉上提取枚舉值
                List<SourceEnumValue> enumValueList = classInfo.getSourceClass().getEnumValueList();
                // 遍歷枚舉值
                for (SourceEnumValue sourceEnumValue : enumValueList) {
                    EnumValueEntity enumValueEntity = new EnumValueEntity();
                    // 獲取枚舉值名字
                    enumValueEntity.setName(sourceEnumValue.getName());
                    // 獲取枚舉值描述
                    enumValueEntity.setDesc(sourceEnumValue.getDesc());
                    // 獲取枚舉值順序
                    enumValueEntity.setOrdinal(sourceEnumValue.getOrdinal());
                    List<EnumValueFieldEntity> fieldList = new ArrayList<>();
                    // 獲取枚舉值構造列表
                    if(BlankAide.isNotBlank(sourceEnumValue.getFieldList())) {
                        for (SourceEnumValueField enumValueField : sourceEnumValue.getFieldList()) {
                            EnumValueFieldEntity fieldEntity = new EnumValueFieldEntity();
                            fieldEntity.setName(enumValueField.getName());
                            fieldEntity.setValue(enumValueField.getValue());
                            fieldList.add(fieldEntity);
                        }
                    }
                    enumValueEntity.setFieldList(fieldList);
                    valueList.add(enumValueEntity);
                }
                enumEntity.setValueList(valueList);
                entityList.add(enumEntity);
            }

            @Override
            public Map<String, Object> getAttribute() {
                // 按key - value 輸出給mvl,在mvl就能通過該key獲取到對應對象
                Map<String, Object> map = new HashMap<>();
                map.put("entityList", entityList);
                return map;
            }

        };
    }

    /** 掃描過濾器 */
    @Override
    protected ClassFilter createClassFilter() {
        return ClassFilterHelper.ofInclude(new Predicate<ScanClassInfo>() {
            @Override
            public boolean test(ScanClassInfo scanClassInfo) {
                // 判斷是否枚舉
                return scanClassInfo.getSourceClass().getClassType().isEnum();
            }
        });
    }

}

插件字段描述

    /** 任務id */
    private String id;

    /** 輸出路徑 */
    protected String outPutDirection;

    /** 源文件路徑 (sourcePath和classPaths二選一)*/
    protected String sourcePath;

    /** class文件路徑(sourcePath和classPaths二選一) */
    protected String[] classPaths;

    /** 搜索的包路徑(可空) */
    protected String[] basePackages;

    /** 依賴路徑(可空) */
    protected String[] dependencyPaths;

    /** mvel文件地址(系統路徑或者ClassLoader下資源名) */
    protected String mvlPath;

    /** mvel表達式 (mvlPath和mvlText二選一)*/
    protected String mvlText;

    /** 是否打印參數 */
    protected boolean logParam;

    /** 輸出文件名 */
    protected String outPutFileName;

    /** 設置打印等級 ERROR,WARN,INFO,DEBUG,TRACE */
    protected String logLevel;

    /** 聚合輸出 */
    protected boolean combination = true;

結語

有個maven插件的支持,你就會發現代碼解析就是這么簡單的事,那剩下的就是通過根據不同場景進行定制開發了,比如提取DO中字段的注釋然后生成SQL腳本,提取接口生成描述腳本等等等

如果這篇文章對你有幫助請給個star


image.png
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容