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
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,702評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,143評論 3 415
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,553評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,620評論 1 307
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,416評論 6 405
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 54,940評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,024評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,170評論 0 287
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,709評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,597評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,784評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,291評論 5 357
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,029評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,407評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,663評論 1 280
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,403評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,746評論 2 370

推薦閱讀更多精彩內容