sourcetip

스프링 부트 스타터에서 아티팩트 ID 및 버전 가져오기

fileupload 2023. 10. 25. 23:41
반응형

스프링 부트 스타터에서 아티팩트 ID 및 버전 가져오기

저는 현재 실행 중인 애플리케이션에 대한 메타 데이터가 포함된 Restful 웹 서비스를 호스팅할 Spring Boot Starter를 개발하고 있습니다.

mainfest 파일에서 artifactId와 versionId를 추출하는 데 어려움을 겪고 있습니다.제 문제는 메인 테스트 어플리케이션 이전에 자동 구성 클래스가 로드되고 있어서 매니페스트를 아직 검색할 수 없는 것 같습니다.문제에 대해 잘못된 각도에서 접근하는 것인지에 대한 제 논리가 올바른지 확신할 수 없습니다.

저는 원래 설정을 위해 다음 자습서를 따라 했습니다.

이로써 저는 3개의 프로젝트를 분리하게 되었습니다.

Generic Spring Services with no context AutoConfiguration project for these services Spring Boot starter

최종 결과로 스타터와 테스트 프로젝트를 짝지었습니다.

현재 maven은 manifest 파일을 생성하기 위해 spring boot과 함께 사용되고 있습니다.

Implementation-Title: MyExampleProjectWithCustomStarter Implementation-Version: 0.0.1-SNAPSHOT Archiver-Version: Plexus Archiver Built-By: mcf Implementation-Vendor-Id: com.coolCompany Spring-Boot-Version: 1.5.4.RELEASE Implementation-Vendor: Pivotal Software, Inc. Main-Class: org.springframework.boot.loader.JarLauncher Start-Class: com.coolcompany.SpringBootExampleApplication Spring-Boot-Classes: BOOT-INF/classes/ Spring-Boot-Lib: BOOT-INF/lib/ Created-By: Apache Maven 3.5.0 Build-Jdk: 1.8.0_131 Implementation-URL: http://someurl

그러나 일반 서비스 패키지에서 예제 프로젝트의 매니페스트 파일을 찾으려 하면 파일을 찾을 수 없습니다.

  private String getApplicationVersion(String applicationName, List<Attributes> manifests) {
    String unknownVersion = "0.0.0-UNKNOWN";

    for (Attributes attr : manifests) {
      String title = attr.getValue(IMPL_TITLE);
      String version = attr.getValue(IMPL_VERSION);
      if (version != null) {
        if (applicationName.equalsIgnoreCase(title)) {
          return title + ' ' + version;
        }
      }
    }
    log.warn(
        "Could not find MANIFEST file with '" + applicationName + "' as Implementation-Title."
        + " Meta-API will return buildVersion '" + unknownVersion + "'.");

    return applicationName + ' ' + unknownVersion;
  }

  private List<Attributes> loadManifestFiles() {
    List<Attributes> manifests = new ArrayList<>();
    try {
      Enumeration<URL> resources =
          Thread.currentThread().getContextClassLoader().getResources("/META-INF/MANIFEST.MF");
      while (resources.hasMoreElements()) {
        URL url = resources.nextElement();
        try (InputStream is = url.openStream()) {
          manifests.add(new Manifest(is).getMainAttributes());
          System.out.println("Manifest size:" + manifests.size());
        } catch (IOException e) {
          log.error("Failed to read manifest from " + url, e);
        }
      }
    } catch (IOException e) {
      log.error("Failed to get manifest resources", e);
    }
    return manifests;
  }

현재 매니페스트 구현-제목:

Spring Boot Web Starter Spring Boot Starter Spring Boot Spring Boot AutoConfigure Spring Boot Logging Starter null null jcl-over-slf4j null log4j-over-slf4j null Spring Boot Tomcat Starter Apache Tomcat Apache Tomcat Apache Tomcat hibernate-validator null JBoss Logging 3 ClassMate jackson-databind Jackson-annotations Jackson-core spring-web spring-aop spring-beans spring-context spring-webmvc spring-expression Spring Boot Actuator Starter Spring Boot Actuator null ** MyCustom-spring-boot-starter ** MyGenericSpringService null null null Metrics Core JVM Integration for Metrics null null Jackson datatype: JSR310 ** MyService-spring-boot-autoconfigure slf4j-api spring-core ** 내 예제 프로젝트 누락사용자 지정 스타터 사용

매니페스트 레코드 수: 44

많은 노력 끝에 놀랍도록 간단한 답을 찾았습니다.스프링 부트 액츄에이터가 정보를 얻는 방법입니다.

Spring Boot Maven 플러그인은 build-info 목표를 갖추고 있습니다.이 목표가 메인 프로젝트에서 트리거되는 한 스프링에는 빌드 속성 클래스가 있습니다.

            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <id>build-info</id>
                        <goals>
                            <goal>build-info</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

다음과 같이 스타터의 속성에 액세스할 수 있습니다.

@Autowired
BuildProperties buildProperties;

...
buildProperties.getArtifact();
buildProperties.getVersion();

플러그인에서 추가 속성을 지정할 수도 있습니다.자세한 내용은 플러그인 설명서 참조: https://docs.spring.io/spring-boot/docs/current/maven-plugin/build-info-mojo.html

불행히도 올바른 매니페스트에 액세스할 수 없는 이유를 완전히 이해할 수 없었지만, 이 문제를 해결하려는 다른 사람에게 도움이 될 것입니다.

다른 대답은 완전히 맞습니다.메이븐 대신 그래들을 사용할 경우 다른 사람들이 이 질문을 찾을 수 있습니다.

빌드 정보를 생성하는 것은 이것을 당신의 것에 추가하는 것만큼 간단합니다.build.gradle파일:

plugins {
    id 'org.springframework.boot' version '<your-boot-version>.RELEASE'
}

// ...    

springBoot {
    buildInfo()
}

사용자 지정 속성을 전달하려는 경우:

springBoot {
    buildInfo {
        properties {
            additional = [
                'property.name': 'property value',
                'other.property': 'different.value'
            ]
        }
    }
}

그럼 자바 코드에서 사용하는 것은 사용하는 것과 같습니다.BuildProperties. 플러그인에 대한 자세한 내용은 이 안내서에서 확인할 수 있습니다.

언급URL : https://stackoverflow.com/questions/44786871/getting-artifactid-and-version-in-spring-boot-starter

반응형