我在我的Spring Boot应用程序中使用bootstrap.yml文件定义了一个应用程序名称。
spring:
application:
name: abc
在运行时/以编程的方式,我如何获取此应用程序名称?
我在我的Spring Boot应用程序中使用bootstrap.yml文件定义了一个应用程序名称。
spring:
application:
name: abc
在运行时/以编程的方式,我如何获取此应用程序名称?
您应该能够使用@Value注释来访问您在属性/YAML文件中设置的任何属性:
@Value("${spring.application.name}")
private String appName;
@Autowired
private ApplicationContext applicationContext;
...
this.applicationContext.getId();
请找到这个:
# IDENTITY (ContextIdApplicationContextInitializer)
spring.application.name=
spring.application.index=
在Spring Boot中,参考手册请见Reference Manual。
随后附上ContextIdApplicationContextInitializer
类的源代码:
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
applicationContext.setId(getApplicationId(applicationContext.getEnvironment()));
}
默认情况下是这样的:
/**
* Placeholder pattern to resolve for application name
*/
private static final String NAME_PATTERN = "${vcap.application.name:${spring.application.name:${spring.config.name:application}}}";
getApplicationName()
不返回任何内容,而getApplicationId()
返回应用程序的名称,该名称使用spring.application.name
属性设置。 - Jan BodnargetId()
returns a combination of the value of spring.application.name
and spring.application.index
. if no index value is set, it is defaulted. in my case calling getId()
returns my-application-1
when the value of spring.application.name
is my-application
- loesak在Spring Boot中,当引用配置属性时,不建议使用@Value
注解,并且因为applicationContext.getId();
不总是返回spring.application.name
的值,所以另一种方法是直接从Environment获取该值。
private final Environment environment;
...
public MyBean(final Environment environment) {
this.environment = environment;
}
...
private getApplicationName() {
return this.environment.get("spring.application.name");
}
@Value
注解直接按名称访问属性。如果该属性未设置或类型不符合预期,则应用程序在执行运行时操作时可能会失败。这还会使查找此类配置的使用方式更加困难。 - loesak#{myConfigProps.myConfig}
从bean中访问配置属性。 - loesak@PropertySource("classpath:application.properties")
@RunWith(SpringRunner.class)
@SpringBootTest
....
这篇文章有些年头了,但我讨厌未回答的问题。因此,请使用以下代码片段:
@Value("${spring.application.name [: defaultValue]}")
private String appName;
方括号内的内容是可选的。
我找到了一种非常丑陋的方法来解决这个问题,但它有效,所以我不再继续搜索。也许这会帮助到某些人。
基本原理是Spring Environment将值存储在propertySource中。似乎引导配置存储在ResourcePropertySource中,因此您可以从中获取它。对于我来说,它目前正在抛出异常,但然后我可以从异常中获取值,所以我没有进一步查看:
try {
this.environment.getProperty("name", ResourcePropertySource.class);
} catch (ConversionFailedException e) {
String res = (String)e.getValue();
}
然后你可以对每个你感兴趣的属性都这样做。
就像我说的那样,虽然不太美观,但它能正常工作。
spring.config.name
为 "bootstrap"(默认为 "application"),或者通过使用spring.config.location
明确指定不同的配置来进一步进行设置。 - Ophir Radnitz