2015-09-02 54 views
0

其實我更喜歡MANIFEST.MF文件中關於這個類的jar的'implementation version'信息。我需要提供諸如默認清單servlet之類的東西,我還將提供buildnumber-maven-plugin提供的SCM提交版本。有沒有簡單的方法來注入主應用程序類?如何注入Spring Boot的SpringApplication的mainApplicationClass?

+0

我真的不知道該buildnumber - Maven的插件。有一種簡單的方法可以使用執行器通過http/jmx公開自定義信息(參見http://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html的第40.4節)。信息必須來自spring-boot環境變量。這個文檔解釋了maven在構建過程中寫入你的application.properties的一種方式(40.4.1:使用Maven進行自動屬性擴展) –

回答

1

您可以使用此插件創建屬性文件whitch你可以在Spring中簡單地理解爲任何其他屬性文件。

有「buildNumberPropertiesFileLocation」選項,你可以指定你的屬性文件的位置。只需將它放在src/main/resources/version.properties中,並在您的spring應用程序中將其作爲常規屬性源讀取即可。您也可以指定屬性名稱。

只需選中文檔爲可用的選項:buildnumber-maven-plugin docs

您可以使用屬性佔位符

<bean 
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 

    <property name="location"> 
     <value>version.properties</value> 
    </property> 
</bean> 

或使用註解讀取屬性:

@PropertySource({ "classpath:version.properties" }) 
@Configuration 
class SomeConfigClass {} 

然後你就可以將屬性簡單地注入到您的服務類別/控制器

@Value("${project.version}") 
private String projectVersion; 

我已經檢查了Spring啓動代碼,我認爲主應用程序類只用於日誌記錄目的,所以如果你想在運行時讀取它,你將不得不以某種方式將它注入應用程序上下文或定義系統屬性,如 將在運行時讀取。

2

你有沒有簡單地試圖定義MANIFEST.MF財產來源,然後就自動裝配值?

@SpringBootApplication 
@PropertySource("META-INF/MANIFEST.MF") 
public class Application implements CommandLineRunner { 

    @Value("${Spring-Boot-Version:notfound}") 
    String springBootVersion; 

    @Value("${Implementation-Version:notfound}") 
    String implementationVersion; 

    public static void main(String[] args) { 
     SpringApplication.run(Application.class, args); 
    } 

    @Override 
    public void run(String... args) throws Exception { 
     System.out.println("springBootVersion is " + springBootVersion); 
     System.out.println("implementationVersion is " + implementationVersion); 
    } 

} 

這將打印:

springBootVersion is 1.2.5.RELEASE 
implementationVersion is 0.1.0 

MANIFEST.MF已經是有點yaml格式和引導理解它。

+0

不幸的是,META-INF/MANIFEST.MF類路徑資源可能由許多不同的jar提供,我的應用程序。這是相當不可預知的哪一個將被加載。 – morisil

相關問題