前言
最近寫代碼,看到別人寫的讀取application.yml
配置文件中數據,寫的挺規范,挺好的;雖然之前也讀取過yml文件,但用的其他方法,沒這個規范,所以記錄下
正文
假設要讀取視頻地址,即http://192.168.10.5:8088/debug/api/video
下面是application.yml
video:# 視頻服務的地址server:url: http://192.168.10.5:8088prefix: /debug/api/video
項目中新建一個config
目錄,可以定義一個類,按配置文件取名,叫VideoServerProperties
@Data
@Component
@ConfigurationProperties(prefix = "video.server")
public class VideoServerProperties {// 字段和配置文件中的對應private String url;private String prefix;@PostConstructpublic 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;@Autowiredpublic VideoServiceImpl(VideoServerProperties videoProperties) {this.videoServerProperties = videoProperties;}private void test(){// 使用配置文件中的內容String url = videoServerProperties.getServerUrl();System.out.println(url);}}