方式一
使用@Value方式(常用)
@Value("${test.msg}")
private String msg;
在yml配置文件中
test :
msg : hello world
测试如下
System.out.println(msg);
hello world
方式二
使用Environment方式
@RestController
public class WebController {
@Autowired
private Environment env;
public static void main(String[] args) {
System.out.println(env.getProperty("test.msg"));
}
}
测试如下
hello world
方式三
@Data
@Configuration
@ConfigurationProperties(prefix = "weather")
@Component
public class WeatherAttributes {
private String city_name;
private String weather_Key;
}
yml文件如下
weather:
city_name: test
weather_Key: test
通过WeatherAttributes中get方法获取属性值即可。