最近在开发过程,发现java项目中的依赖包源码没有导入,因此debug的过程中,跟踪变量问题寸步难行。查看了相关的maven文档,常用的有如下三种方式来下载源码:

    • mvn 命令
    • 全局配置setting.xml
    • 使用maven-dependency-plugin

mvn 命令

下载源码时可以通过配置不同的参数来决定要不要下载java doc

# 只下载源码
mvn dependency:sources
# 只下载java doc
mvn dependency:resolve -Dclassifier=javadoc
# 源码和java doc都下载
mvn dependency:sources dependency:resolve -Dclassifier=javadoc

可以这么说,这是通过手动的方法下载源码,如果每个项目都要运行命令,还是有点麻烦的。因此可以看一下下面两种方法。

全局配置setting.xml

在~/m2/setting.xml中加入如下配置,这就可以保证使用此配置文件的项目都可以自动下载源码。

<settings>
    <!-- ... other settings omitted ... -->
    <profiles>
        <profile>
            <id>downloadSources</id>
            <properties>
                <downloadSources>true</downloadSources>
                <downloadJavadocs>true</downloadJavadocs>
            </properties>
        </profile>
    </profiles>

    <activeProfiles>
        <activeProfile>downloadSources</activeProfile>
    </activeProfiles>
</settings>

使用maven-dependency-plugin

可以根据自己项目的需要配置加入插件,如果公司所有的项目都要下载源码,那么可以配置到parent pom.xml中。

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>3.1.2</version>
            <executions>
                <execution>
                    <goals>
                        <goal>sources</goal>
                        <goal>resolve</goal>
                    </goals>
                    <configuration>
                        <classifier>javadoc</classifier>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

当然,还有其他的方式,例如官网下载,然后放入repository中。或者在IDE上进行相关的配置等。最后希望本文能帮助大家,祝大家在IT之路上少走弯路,一路绿灯不堵车,测试一性通过,bug秒解!

更多推荐

maven 下载依赖源码