In the world of Java development, we often find ourselves working with third-party libraries that aren't available in public Maven repositories. Today, we'll explore how to publish these closed-source JAR files to GitHub Packages and use them in other Maven projects.
Why GitHub Packages?
GitHub Packages provides a convenient way to host and manage your private dependencies. It integrates seamlessly with your GitHub repositories and offers fine-grained access control.
The Traditional Approach
Typically, publishing to GitHub Packages involves modifying your settings.xml
file with your GitHub credentials. While effective, this method isn't always ideal, especially in CI/CD environments or when you prefer keeping credentials separate from your project configuration.
A More Flexible Solution: Environment Variables
Let's walk through a more flexible approach using environment variables. This method allows you to publish and consume packages without modifying your Maven settings file.
Step 1: Set Up Environment Variables
First, set the following environment variables:
export GITHUB_ACTOR=YOUR_GITHUB_USERNAME
export GITHUB_TOKEN=YOUR_PERSONAL_ACCESS_TOKEN
Ensure your personal access token has the write:packages
and read:packages
scopes.
Step 2: Configure Your Project's pom.xml
Modify your pom.xml
to use these environment variables:
<project>
...
<distributionManagement>
<repository>
<id>github</id>
<name>GitHub Packages</name>
<url>https://maven.pkg.github.com/${env.GITHUB_ACTOR}/YOUR_REPOSITORY</url>
</repository>
</distributionManagement>
...
</project>
Step 3: Deploy Your JAR
Use this command to deploy your third-party JAR:
mvn deploy:deploy-file -DgroupId=com.example -DartifactId=your-artifact -Dversion=1.0.0 -Dpackaging=jar -Dfile=/path/to/your/jar/file -DrepositoryId=github -Durl=https://maven.pkg.github.com/${GITHUB_ACTOR}/YOUR_REPOSITORY
Step 4: Consume the Package
In projects where you want to use this JAR, add this to your pom.xml
:
<project>
...
<repositories>
<repository>
<id>github</id>
<url>https://maven.pkg.github.com/${env.GITHUB_ACTOR}/YOUR_REPOSITORY</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.example</groupId>
<artifactId>your-artifact</artifactId>
<version>1.0.0</version>
</dependency>
</dependencies>
...
</project>
Benefits of This Approach
- Flexibility: Easy to use in different environments without modifying Maven settings.
- Security: Keeps credentials separate from project files.
- CI/CD Friendly: Simplifies integration with various CI/CD pipelines.
Conclusion
By leveraging environment variables, we've streamlined the process of publishing and consuming third-party JARs via GitHub Packages. This approach offers greater flexibility and security, making it an excellent choice for teams looking to manage their private dependencies efficiently.
Remember, while this method is powerful, always handle your personal access tokens with care.