方式一
使用@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方法获取属性值即可。
本文介绍了在SpringBoot项目中,通过@Value注解、Environment对象以及@ConfigurationProperties注解三种方式读取配置文件的方法,并提供了具体的代码示例。
3718

被折叠的 条评论
为什么被折叠?



