![](/img/trans.png)
[英]How to access Class member variables from SpringApplication in Spring Boot
[英]How to inject mainApplicationClass of spring boot's SpringApplication?
實際上,我對與此類jar關聯的MANIFEST.MF文件中的“實現版本”信息更感興趣。 我需要提供類似默認清單servlet的內容,在這里我還將具有buildnumber-maven-plugin提供的SCM提交版本。 有沒有簡單的方法可以注入主應用程序類?
您是否只是嘗試將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
格式,引導程序可以理解。
您可以使用此插件創建屬性文件,可以像其他任何屬性文件一樣在春季輕松讀取。
有“ buildNumberPropertiesFileLocation”選項,您可以在其中指定屬性文件的位置。 只需將其放在src / main / resources / version.properties中,並在您的spring應用程序中將其作為常規屬性源讀取即可。 您還可以指定屬性名稱。
只需檢查文檔以獲取可用選項: buildnumber-maven-plugin文檔
您可以使用屬性占位符讀取屬性
<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引導代碼,並且我認為主應用程序類僅用於日志記錄目的,因此,如果要在運行時讀取它,則必須以某種方式將其注入應用程序上下文或定義將在運行時讀取的系統屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.