如何以编程方式访问Spring Boot应用程序的名称?

yat*_*gan 25 spring spring-boot

我在spring boot应用程序中使用bootstrap.yml文件定义了一个应用程序名称.

spring:
  application:
    name: abc
Run Code Online (Sandbox Code Playgroud)

如何在运行时/编程期间获取此应用程序名称?

Dan*_*one 30

您应该能够使用@Value批注来访问您在属性/ YAML文件中设置的任何属性:

@Value("${spring.application.name}")
private String appName;
Run Code Online (Sandbox Code Playgroud)

  • 这适用于 application.yml/application.properties,但不适用于 bootstrap.yml。有什么需要配置的吗?一些注释,某处? (2认同)

Art*_*lan 12

@Autowired
private ApplicationContext applicationContext;    
...
this.applicationContext.getId();
Run Code Online (Sandbox Code Playgroud)

请找到这个:

# IDENTITY (ContextIdApplicationContextInitializer)
spring.application.name=
spring.application.index=
Run Code Online (Sandbox Code Playgroud)

在Spring Boot 参考手册中.

并按照ContextIdApplicationContextInitializer该类的源代码:

@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    applicationContext.setId(getApplicationId(applicationContext.getEnvironment()));
}
Run Code Online (Sandbox Code Playgroud)

默认行为是这样的:

/**
 * Placeholder pattern to resolve for application name
 */
private static final String NAME_PATTERN = "${vcap.application.name:${spring.application.name:${spring.config.name:application}}}";
Run Code Online (Sandbox Code Playgroud)

  • 应用程序 ID 是应用程序名称。对我来说,“getApplicationName()”不返回任何内容,“getApplicationId()”返回应用程序的名称,与“spring.application.name”属性设置的一样。 (2认同)

loe*_*sak 5

由于@Value在 Spring Boot 中不鼓励在引用配置属性时使用注解,并且因为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");
}
Run Code Online (Sandbox Code Playgroud)

另一种可能的方法是创建您自己的 ConfigurationProperties 类来访问该值。

我并不是说这些是最好的方法,我希望/希望有更好的方法,但这是一种方法。

  • 我发现:“使用 @Value("${property}") 注释来注入配置属性有时可能很麻烦,特别是如果您正在使用多个属性或您的数据本质上是分层的”以及`之间差异的讨论@Value` 和 `@ConfigurationProperties` https://docs.spring.io/spring-boot/docs/2.4.x/reference/htmlsingle/#boot-features-external-config-typesafe-configuration-properties。 (2认同)