Spring Boot可使用注解的方式将自定义的properties(yml)文件映射到实体bean中,yml文件内容如下:
system:
filePath: systemFilePath
photoPath: E:/
实体类中使用@ConfigurationProperties(prefix = "system") 注解,prefix = "system" 用来选择哪个属性的prefix名字来绑定,即对应yml文件中的system属性。
package com.touchspring.isite.base.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "system")
public class SystemConfig {
private String filePath;
private String photoPath;
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public String getPhotoPath() {
return photoPath;
}
public void setPhotoPath(String photoPath) {
this.photoPath = photoPath;
}
}
其他地方如何使用定义好的prefix属性,通过@Autowired 注入bean,即可调用yml文件定义的prefix属性。
package com.touchspring.isite.controller;
import com.touchspring.core.mvc.ui.ResultData;
import com.touchspring.isite.base.config.SystemConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ConfigController {
@Autowired
private SystemConfig systemConfig;
@GetMapping("prefix")
public ResultData getSystemConfigPrefix(){
String prefix = systemConfig.getFilePath();
System.out.println("prefix:---"+ prefix); // prefix:prefix:--- system.filePath
return ResultData.ok().putDataValue("prefix",prefix);
}
}