springboot中yml配置文件属性读取
方式一 : 通过Environment获取
yml文件:
goto:
server:
url: http://10.204.4.186:9010
Environment两种使用方式
- Autowired注入
@Autowired
private Environment env;
// ......
String prefix = env.getProperty("goto.server.url");
- 使用@Configuration注解,并实现EnvironmentAware接口
package com.metarnet.kpi.utils;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
/**
* @ClassName YmlUtil
* @Description 获取yml中的属性值
* @Author wangyj
* @Date 19/11/18
*/
@Configuration
public class YmlUtil implements EnvironmentAware {
private static Environment env;
@Override
public void setEnvironment(Environment environment) {
env = environment;
}
public static String getProperty(String name) {
return env.getProperty(name);
}
}
方式二 : @ConfigurationProperties(prefix = “toss”)
yml文件:
toss:
# 文件上传路径P
profile: D:/eclipse_workspace/kpi/profile/system/
java代码:
package com.metarnet.kpi.$config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @ClassName TossConfig
* @Description
* @Author wangyj
* @Date 19/10/24 10:05
*/
@Component
@ConfigurationProperties(prefix = "toss")
public class TossConfig {
/**文件上传路径*/
private static String profile;
public static String getProfile() {
return profile;
}
public void setProfile(String profile) {
TossConfig.profile = profile;
}
public static String getDownloadPath(){
return profile + "download/";
}
}
方式三 : @Value
暂时没有使用到这种方式
springboot多配置文件(多个yml)
如下图 , 是用了多个自定义配置文件
需要 注意 ,自定义yml文件名称需要遵循 application-*.yml
然后需要在application.yml文件中添加:
spring.profiles.include:goto,excel
spring:
profiles:
# active: development
active: production
include: goto,excel