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)
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)
由于@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 类来访问该值。
我并不是说这些是最好的方法,我希望/希望有更好的方法,但这是一种方法。
| 归档时间: |
|
| 查看次数: |
25872 次 |
| 最近记录: |