spring boot之maven-wrapper

Spring Boot有很多功能特性值得借鑑和學習,很多玩Spring Boot的人知道不需要安裝Tomcat很方便,其實並沒有發現Maven也是不需要提前安裝。它這樣做的好處在於解決了開發環境maven版本不一致導致的各種問題,spring boot中集成了maven-wrapper的確比較務實。

它是什麼

相信大家都用到spring的腳手架:https://start.spring.io/ 來生成Spring Boot項目,而項目的根目錄中會多幾個文件:

cmd > C:\Users\alex\Desktop\demo> tree /f
│  mvnw            //linux-shell
│  mvnw.cmd        //window-cmd
│  pom.xml
├─.mvn
│  └─wrapper
│          maven-wrapper.jar
│          maven-wrapper.properties
│          MavenWrapperDownloader.java
├─src

maven-wrapper解決了2個問題:
1.可以爲某個Java工程指定某個特定Maven版本,避免因爲版本差異引起的詭異錯誤,這樣就統一該項目的開發環境;
2.不再需要提前安裝Maven,簡化了開發環境的配置;

玩法及原理

1.當前項目(spring boot)

在項目目錄下執行mvnw clean,其實就是將之前你熟悉的mvn替換爲mvnw命令即可,一點也不復雜。

mvnw第一次運行會檢測$USER_HOME/.m2/wrapper/dists 目錄下是否有maven-wrapper.properties中指定的Maven版本,如果沒有就自動下載。

此時你會問下載後的maven會在哪裏?

一般會在${user.home}\.m2\wrapper\dists目錄,我的機器是在:C:\Users\alex\.m2\wrapper\dists\apache-maven-3.6.2-bin\795eh28tki48bv3l67maojf0ra

如何調整版本呢?

具體可參與maven-wrapper.properties中配置:
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.2/apache-maven-3.6.2-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar

原理:mvnw.cmd邏輯也不復雜,先將maven-wrapper.jar添加到classpath,再運行MavenWrapperDownloader#main

public class MavenWrapperDownloader {
    private static final String WRAPPER_VERSION = "0.5.5";
    /**
     * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
     */
    private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
        + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";

    /**
     * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
     * use instead of the default one.
     */
    private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
            ".mvn/wrapper/maven-wrapper.properties";

    /**
     * Path where the maven-wrapper.jar will be saved to.
     */
    private static final String MAVEN_WRAPPER_JAR_PATH =
            ".mvn/wrapper/maven-wrapper.jar";

    /**
     * Name of the property which should be used to override the default download url for the wrapper.
     */
    private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";

    public static void main(String args[]) {
        System.out.println("- Downloader started");
        File baseDirectory = new File(args[0]);
        System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());

        // If the maven-wrapper.properties exists, read it and check if it contains a custom
        // wrapperUrl parameter.
        File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
        String url = DEFAULT_DOWNLOAD_URL;
        if(mavenWrapperPropertyFile.exists()) {
            FileInputStream mavenWrapperPropertyFileInputStream = null;
            try {
                mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
                Properties mavenWrapperProperties = new Properties();
                mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
                url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
            } catch (IOException e) {
                System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
            } finally {
                try {
                    if(mavenWrapperPropertyFileInputStream != null) {
                        mavenWrapperPropertyFileInputStream.close();
                    }
                } catch (IOException e) {
                    // Ignore ...
                }
            }
        }
        System.out.println("- Downloading from: " + url);

        File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
        if(!outputFile.getParentFile().exists()) {
            if(!outputFile.getParentFile().mkdirs()) {
                System.out.println(
                        "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
            }
        }
        System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
        try {
            downloadFileFromURL(url, outputFile);
            System.out.println("Done");
            System.exit(0);
        } catch (Throwable e) {
            System.out.println("- Error downloading");
            e.printStackTrace();
            System.exit(1);
        }
    }

    private static void downloadFileFromURL(String urlString, File destination) throws Exception {
        if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
            String username = System.getenv("MVNW_USERNAME");
            char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
            Authenticator.setDefault(new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });
        }
        URL website = new URL(urlString);
        ReadableByteChannel rbc;
        rbc = Channels.newChannel(website.openStream());
        FileOutputStream fos = new FileOutputStream(destination);
        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        fos.close();
        rbc.close();
    }

}

2.全局命令

還可以mvn -N io.takari:maven:wrapper -Dmaven=3.3.3表示我們期望使用的Maven的版本爲3.3.3,將mvnw提升爲全局命令,個人感覺意義不大,它最大的貢獻在於保留及堅持個性化。

3.idea插件maven-wrapper-support

它需要結合當前項目(找maven-wrapper.properties配置)來使用。

maven-wrapper-support的邏輯也不復雜:會監測項目下的.mvn/wrapper/maven-wrapper.properties中的distributionUrl屬性值,且自動下載maven版本到用戶目錄.m2/wrapper目錄中,並且改變setting->build->build Tools ->maven-> maven home directory的值,但執行的命令是原生mvn的命令,而不是項目中下的mvnw命令。

原理:具體驗證可查看plugin安裝目錄一般爲:idea.config.path=${user.home}/.IntelliJIdea/config,比如我的:C:\Users\alex\.IntelliJIdea2018.3\config\plugins\maven-wrapper-support\lib中的maven-wrapper-support-0.5.1.jar代碼MavenWrapperProjectComponent.class。

public class MavenWrapperProjectComponent extends AbstractProjectComponent {
    private VirtualFile wrapperSettings;
    private Logger log = Logger.getInstance(this.getClass());

    public MavenWrapperProjectComponent(Project project) {
        super(project);
    }

    private void applyWrapper() {
        if (this.wrapperSettings != null) {
            StringBuilder output = new StringBuilder();
            WrapperExecutor wrapperExecutor = WrapperExecutor.forWrapperPropertiesFile(new File(this.wrapperSettings.getPath()), output);
            File mavenUserHome = new File(System.getProperty("user.home") + "/.m2");
            Installer installer = new Installer(new DefaultDownloader("mvnw", "0.4.0"), new PathAssembler(mavenUserHome));

            try {
                File mavenHome = installer.createDist(wrapperExecutor.getConfiguration());
                this.changeMavenHomeTo(mavenHome.getAbsolutePath(), "maven wrapper defined in " + this.wrapperSettings.getPath());
            } catch (Exception var6) {
                this.log.error(var6);
            }

        }
    }

    private void changeMavenHomeTo(String mavenPath, String message) {
        MavenGeneralSettings generalSettings = MavenProjectsManager.getInstance(this.myProject).getGeneralSettings();
        if (generalSettings != null) {
            String oldMavenHome = generalSettings.getMavenHome();
            if (!mavenPath.equals(oldMavenHome)) {
                generalSettings.setMavenHome(mavenPath);
                this.log.info("Maven changed to " + message);
                Bus.notify(new Notification("maven-wrapper", "Maven changed", "Maven changed to " + message, NotificationType.INFORMATION));
            }
        }
    }

    public void projectOpened() {
        VirtualFileManager.getInstance().addVirtualFileListener(new com.blackbuild.intellij.wavenwrappersupport.MavenWrapperProjectComponent.ChangeListener(this));
        this.wrapperSettings = this.myProject.getBaseDir().findFileByRelativePath(".mvn/wrapper/maven-wrapper.properties");
        this.applyWrapper();
    }

    @NotNull
    public String getComponentName() {
        String var10000 = this.getClass().getName();
        if (var10000 == null) {
            $$$reportNull$$$0(0);
        }

        return var10000;
    }
}

注意事項

1.distributionUrl下載會比較慢

建議替換爲:http://www-us.apache.org/dist/maven/maven-3/3.5.4/binaries/apache-maven-3.5.4-bin.zip

2.mvnw.bat中執行老版本的maven可能會報錯:"Error: M2_HOME is set to an invalid directory"

Maven早期版本不叫mvn.cmd,而是叫mvn.bat,找到代碼替換掉即可

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章