创建ApplicationConfigure类
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
public class ApplicationConfigure {
private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationConfigure.class);
/**
* 获取配置
*/
@Autowired
private Environment env;
/**
* 获取配置文件值
* @param key 键
* @param defaultValue 默认值
* @return
*/
public String getProperty(String key, String defaultValue) {
RelaxedPropertyResolver propertyResolver = new RelaxedPropertyResolver(env);
String value = propertyResolver.getProperty(key);
if (null == value || value.length == 0) {
value = defaultValue;
}
LOGGER.debug("{}:{}", key, value);
return value;
}
}
使用
@Controller
public class MyController{
@Autowired
private ApplicationConfigure applicationConfigure;
public void getConfigure(){
applicationConfigure.getProperty("my.root.url", "http://127.0.0.1:8080");
}
}