[英]Spring boot environment variable are not reflecting properly
我正在Spring Boot应用程序上工作,在这里我想通过配置服务器动态地完全外部化环境变量。
所以下面是我编写的代码。
应用程序
package com.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
@Configuration
@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan("com.myPackage, com.util")
@PropertySource("classpath:application.properties")
public class Application extends SpringBootServletInitializer {
static final Logger logger = LoggerFactory.getLogger(Application.class);
public static ApplicationContext ctx;
public static void main(String[] args) throws Exception {
logger.info("Application starting....");
ctx = SpringApplication.run(Application.class, args);
logger.info("Application started successfully....");
}
@Bean
public static PropertySourcesPlaceholderConfigurer
propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
application.properties
server.port=${server.port}
ENDPOINT_SHAN=${name.mya}
配置服务器:
APPLICATION_NAME=myapp
server.port=8081
name.mya=myName
读取属性
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import com.apptium.Application;
@Component("configurationProperties")
public class ConfigurationProperties {
private static Environment prop;
public static String getConfigValue(String key) {
String value = null;
if (prop == null) {
prop = Application.ctx.getBean(Environment.class);
}
if (prop.getProperty(key) != null) {
value = prop.getProperty(key).trim();
}
if (value == null && System.getenv(key) !=null) {
value = System.getenv(key).trim();
}
return value;
}
}
因此,当我尝试获取属性ENDPOINT_SHAN
,它将返回ENDPOINT_SHAN==${name.mya}
但它需要返回ENDPOINT_SHAN==myName
并且也想知道如何正确使用server.port的属性。
无论如何,我想知道如何获取ENDPOINT_SHAN
的实际属性。
您说过name.mya
是在“配置服务器”中定义的,但是您的代码未显示与此服务器建立任何连接。 您需要先从服务器读取它,然后才能解析${name.mya}
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.