前言
最近写代码,看到别人写的读取application.yml
配置文件中数据,写的挺规范,挺好的;虽然之前也读取过yml文件,但用的其他方法,没这个规范,所以记录下
正文
假设要读取视频地址,即http://192.168.10.5:8088/debug/api/video
下面是application.yml
video:
# 视频服务的地址
server:
url: http://192.168.10.5:8088
prefix: /debug/api/video
项目中新建一个config
目录,可以定义一个类,按配置文件取名,叫VideoServerProperties
@Data
@Component
@ConfigurationProperties(prefix = "video.server")
public class VideoServerProperties {
// 字段和配置文件中的对应
private String url;
private String prefix;
@PostConstruct
public void init(){
}
public String getServerUrl(){
return this.url + this.prefix;
}
}
Service层使用即可,这样不单独在service随便写变量,然后用$Value,或者用Environment读取,相对解耦,读取配置属性的都在config目录,便于管理
@Service
public class VideoServiceImpl implements IVideoService {
private final VideoServerProperties videoServerProperties;
@Autowired
public VideoServiceImpl(VideoServerProperties videoProperties) {
this.videoServerProperties = videoProperties;
}
private void test(){
// 使用配置文件中的内容
String url = videoServerProperties.getServerUrl();
System.out.println(url);
}
}