Groovy + Java 混合程式設計方案:GMaven

騷銘科技發表於2022-11-24

Groovy + Java 混合程式設計方案:GMaven

Hava a look

先看效果。在專案中隨便建立一個 SayHiUtil.groovy,然後在main裡面新增個執行列印一下

package com.cmb.lr20.zxb.dialog.utils

class SayHIUtil {

    static def sayHi() {
        println "Hi groovy"
    }
}
public class DialogApplication {

    public static void main(String[] args) {
        SayHIUtil.sayHi();
        SpringApplication.run(DialogApplication.class, args);
    }
}

image.png

DO IT!

使用GMavenPlus,只需加個 plugin 和 dependency 即可:

    

    <dependencies>
        <!-- Groovy -->
        <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy</artifactId>
            <version>3.0.9</version>
        </dependency>
    </dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.codehaus.gmavenplus</groupId>
            <artifactId>gmavenplus-plugin</artifactId>
            <version>1.13.1</version>
            <executions>
                <execution>
                    <goals>
                        <goal>addSources</goal>
                        <goal>addTestSources</goal>
                        <goal>generateStubs</goal>
                        <goal>compile</goal>
                        <goal>generateTestStubs</goal>
                        <goal>compileTests</goal>
                        <goal>removeStubs</goal>
                        <goal>removeTestStubs</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <!-- if including source jars, use the no-fork goals
                     otherwise both the Groovy sources and Java stub sources
                     will get included in your jar -->
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-source-plugin</artifactId>
            <!-- source plugin \> = 2.1 is required to use the no-fork goals -->
            <version>3.2.1</version>
            <executions>
                <execution>
                    <id>attach-sources</id>
                    <goals>
                        <goal>jar-no-fork</goal>
                        <goal>test-jar-no-fork</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

如果遇到編譯問題,應該是source目錄的問題。有兩個解決方法:

  • 將groovy檔案放到 src/main/groovy
  • 在plugin裡面自定義source directory,具體詳見GMavenPlugin的wiki
    image.png

Shell

image.png

image.png

相關文章