Generate source code jar for Maven based project

The “maven-source” plugin is used to pack your source code and deploy along with your project. This is extremely useful, for developers who use your deployed project and also want to attach your source code for debugging.

1. Maven Source Plugin

Add maven-source-plugin in your pom.xml file.

pom.xml

  <build>
	  <plugins>
	    <plugin>
		<groupId>org.apache.maven.plugins</groupId>
		<artifactId>maven-source-plugin</artifactId>
		<executions>
			<execution>
				<id>attach-sources</id>
				<goals>
					<goal>jar</goal>
				</goals>
			</execution>
		</executions>
	   </plugin>
	 </plugins>
  </build>

2. Deploy It

Issue “mvn install” to package and deploy your project to local repository.


D:\mkyongweb-core>mvn install
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building mkyongcore project
[INFO]    task-segment: [install]
[INFO] ------------------------------------------------------------------------
//...
[INFO] [jar:jar {execution: default-jar}]
[INFO] Building jar: D:\mkyongweb-core\target\mkyongcore-1.0.jar
[INFO] Preparing source:jar
[WARNING] Removing: jar from forked lifecycle, to prevent recursive invocation.
[INFO] No goals needed for project - skipping
[INFO] [source:jar {execution: attach-sources}]
[INFO] Building jar: D:\mkyongweb-core\target\mkyongcore-1.0-sources.jar
[INFO] [install:install {execution: default-install}]
[INFO] Installing D:\mkyongweb-core\target\mkyongcore-1.0.jar to D:\maven\repo\com\mky
ong\mkyongcore\1.0\mkyongcore-1.0.jar
[INFO] Installing D:\mkyongweb-core\target\mkyongcore-1.0-sources.jar to D:\maven\repo
\com\mkyong\mkyongcore\1.0\mkyongcore-1.0-sources.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL

3. Output

Browse to your local repository, you will notice two jar files are created

  1. mkyongcore-1.0.jar (classes)
  2. mkyongcore-1.0-sources.jar (source code)
generate source code for maven

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

5 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Keyur Shah
5 years ago

this is not working now. mvn install command is only generating a jar with compiled sources and not for source code. have added a plugin as mentioned in above thread to pom.xml.

Jai
12 years ago

Perfect 🙂

Lee Wasilenko
10 years ago

Is there a way to include only the sources from a particular package or a set of classes?

Moreaki
11 years ago

And how do you remove the dreaded warning?

Vaithi
13 years ago

This is a very clear & straight forward sample. Much helpful. Thanks.