有时spring 项目中需要将配置文件的属性注入到类的静态字段中
例如:文件上传
//文件上传指定上传位置 //resource-dev.properties 有如下参数 #upload UPLOAD_PATH=D:\home\images STATIC_URL=http://127.0.0.1/images/upload/
如果想在类中直接使用,可以通过定义常量类的静态字段来获取
@Component @PropertySource("classpath:dev/resource-dev.properties") public class ConstantsFilename { //Upload常量 public static String UPLOAD_PATH; public static String STATIC_URL; public String getUploadPath() { return UPLOAD_PATH; } //将 set 方法的 static 去掉 @Value("${UPLOAD_PATH}") public void setUploadPath(String uploadPath) { UPLOAD_PATH = uploadPath; } public String getStaticUrl() { return STATIC_URL; } //将 set 方法的 static 去掉 @Value("${STATIC_URL}") public void setStaticUrl(String staticUrl) { STATIC_URL = staticUrl; } }
此时,可以在你的类中直接使用 ConstantsFilename.STATIC_URL 和 ConstantsFilename.UPLOAD_PATH 了。