me mostre o uso do JGitVer em um projeto java 8 e spring boot 2.1.6.RELEASE
- User
me mostre o uso do JGitVer em um projeto java 8 e spring boot 2.1.6.RELEASE
Assistant
JGitVer é uma excelente ferramenta para automação de versionamento baseada no Git! Ele é totalmente compatível com Java 8 e Spring Boot 2.1.6.RELEASE. Vou te mostrar como configurar e usar em um projeto real.
🔧 O que é JGitVer?
JGitVer é uma biblioteca Java que calcula automaticamente a versão do projeto com base no histórico do Git (tags, commits, branches). Ele é uma alternativa moderna ao Maven Release Plugin.
📦 Configuração completa para Spring Boot 2.1.6.RELEASE + Java 8
1.
pom.xmlprincipal<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.exemplo</groupId> <artifactId>meu-projeto-spring</artifactId> <!-- A versão será calculada automaticamente pelo JGitVer --> <version>0</version> <packaging>jar</packaging> <name>Meu Projeto Spring Boot</name> <description>Projeto Spring Boot com JGitVer</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.6.RELEASE</version> <relativePath/> </parent> <properties> <java.version>1.8</java.version> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <!-- Plugin do Spring Boot --> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <!-- JGitVer Maven Plugin --> <plugin> <groupId>fr.brouillard.oss</groupId> <artifactId>jgitver-maven-plugin</artifactId> <version>1.9.1</version> <extensions>true</extensions> <configuration> <!-- Estratégia de versionamento --> <strategy>MAVEN</strategy> <!-- Prefixo das tags (ex: v1.0.0) --> <tagVersionPattern>^v(.*)$</tagVersionPattern> <!-- Usar snapshot para branches que não sejam release --> <nonQualifierBranches>master,main</nonQualifierBranches> <!-- Incluir distância do commit na versão --> <useDistance>true</useDistance> <!-- Incluir hash do commit na versão --> <useGitCommitId>true</useGitCommitId> <!-- Usar dirty marker se houver mudanças não commitadas --> <useDirty>true</useDirty> </configuration> </plugin> <!-- Plugin para exibir a versão calculada --> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <version>3.0.0</version> <executions> <execution> <id>parse-version</id> <phase>validate</phase> <goals> <goal>parse-version</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project>
2. Arquivo de configuração:
.jgitverCrie um arquivo
.jgitverna raiz do projeto para personalizar o comportamento:# Estratégia de versionamento (MAVEN, PATTERN, CONFIGURABLE) strategy=MAVEN # Padrão para extrair versão das tags Git tagVersionPattern=^v(.*)$ # Branches que não devem ter qualificador (ex: -SNAPSHOT) nonQualifierBranches=master,main,release.* # Usar distância do commit na versão useDistance=true # Incluir ID do commit (primeiros 8 caracteres) useGitCommitId=true # Marcar como "dirty" se houver mudanças não commitadas useDirty=true # Ignorar mudanças não commitadas para calcular versão useSnapshot=true
3. Controller de exemplo para testar
package com.exemplo.controller; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class VersionController { @Value("${project.version:unknown}") private String projectVersion; @GetMapping("/version") public String getVersion() { return "Versão do projeto: " + projectVersion; } }
4.
application.properties# Definir a versão do projeto (será substituída pelo JGitVer) project.version=@project.version@ # Configurações do Spring Boot server.port=8080 spring.application.name=meu-projeto-spring # Logs logging.level.com.exemplo=DEBUG
🚀 Como usar no dia a dia
1. Inicializar o repositório Git
git init git add . git commit -m "Initial commit"2. Criar primeira tag
git tag v1.0.03. Verificar a versão calculada
mvn help:evaluate -Dexpression=project.version -q -DforceStdout # Saída: 1.0.04. Fazer novos commits e ver como a versão muda
# Fazer mudanças echo "// Nova funcionalidade" >> src/main/java/Application.java git add . git commit -m "feat: nova funcionalidade" # Ver nova versão mvn help:evaluate -Dexpression=project.version -q -DforceStdout # Saída: 1.0.1-1 (1.0.0 + 1 commit de distância)5. Criar nova release
git tag v1.1.0 mvn help:evaluate -Dexpression=project.version -q -DforceStdout # Saída: 1.1.0
📋 Exemplos de versões geradas
Situação Versão gerada Tag v1.0.0(commit exato)1.0.02 commits após v1.0.01.0.1-2Branch feature/login1.0.1-feature-login-SNAPSHOTMudanças não commitadas 1.0.1-dirtyCom commit ID habilitado 1.0.1-2-a1b2c3d4
🛠️ Comandos úteis
# Ver versão atual mvn help:evaluate -Dexpression=project.version -q -DforceStdout # Compilar com versão automática mvn clean compile # Gerar JAR com versão automática mvn clean package # Executar aplicação Spring Boot mvn spring-boot:run # Ver informações detalhadas do JGitVer mvn fr.brouillard.oss:jgitver-maven-plugin:version
✅ Verificar se está funcionando
- Execute o projeto:
mvn spring-boot:run- Acesse o endpoint de versão:
curl http://localhost:8080/version # Resposta: "Versão do projeto: 1.0.0"- Verifique o JAR gerado:
mvn clean package ls target/ # Arquivo: meu-projeto-spring-1.0.0.jar
🎯 Vantagens do JGitVer
✅ Zero configuração manual de versões no
pom.xml
✅ Compatível com Java 8 e Spring Boot 2.1.6.RELEASE
✅ Versionamento semântico automático
✅ Funciona offline (não depende de serviços externos)
✅ Integra bem com CI/CD (Jenkins, GitHub Actions)
Esse setup vai funcionar perfeitamente com seu ambiente! Quer que eu mostre como integrar com algum pipeline CI/CD específico? 😊
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.