---
# System prepended metadata

title: 將 Java Library 發佈到 GitLab Project 中
tags: [Java, Tips]

---

# 將 Java Library 發佈到 GitLab Project 中

> Ref: https://docs.gitlab.com/ee/user/packages/maven_repository/index.html#getting-started-with-gradle

1. 對 GitLab Project 啟用 Package Manager。  
    > 位於 *Project Settings/General Settings/Visibility, project features, permissions*。
    
    ![Enable packages](https://hackmd.io/_uploads/H1h2wAhh6.png)


2. 到 *User Settings/Access Tokens* 建立 Scopes 為 `api` 的 Token。
    ![建立 PAT](https://hackmd.io/_uploads/Skg5B02np.png)

3. 將建立好的 Token 存入 `~/.gradle/gradle.properties`。
    ```properties
    MyGitLabPrivateToken=<your_private_token>
    ```
    
4. 在 `build.gradle.kts` 中使用 `maven-publish` plugin。
    ```kotlin
    plugins {
        `maven-publish`
        `java-library`
    }
    ```

5. 在 `build.gradle.kts` 中設定 publishing 的資訊。分別填入 `gitlab_url`、`project_id`等資訊。
    ```kotlin
    publishing {
        publications {
            create("MyLibrary", MavenPublication::class) {
                from(components["java"])
            }
        }
        repositories {
            maven {
                url = uri("https://<gitlab_url>/api/v4/projects/<project_id>/packages/maven")
                name = "MyGitLab"
                credentials(HttpHeaderCredentials::class) {
                    name = "Private-Token"
                    value = findProperty("MyGitLabPrivateToken")?.toString()
                }
                authentication {
                    create<HttpHeaderAuthentication>("header")
                }
            }
        }
    }
    ```

6. 執行 `gradle publishMyLibraryPublicationToMyGitLabRepository` 來發佈 package。發佈完成後可在 *Project/Packages* 查看結果。
![圖片](https://hackmd.io/_uploads/SJR8qCh2p.png)


