![](/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.