在系统开发中,我们经常会将本地的图片,文档等文件上传到系统。在之前,我们肯定都是在常量类中定义一个路径地址
public static final String IMAGE_USER_FACE_LOCATION = "E:\\workspace\\images\\foodie\\face"
我们在使用的时候只需要用一个变量接收就可以了。
String fileSpace = IMAGE_USER_FACE_LOCATION;
但是这样有一个问题,比如说我们在本地开发,使用的是window系统的电脑,所以我们的路径写的是E:\workspace\images\foodie\face
但是我们如果将项目部署到linux服务器上,linux机器上是没有盘符这个概念的,根路径就是一个/ 那么我们只能将原先定义的常量注释掉,重新在定义一个新的常量路径。但这种方法肯定不是特别好的。我们可以使用配置文件来进行配置两个路径地址
file-upload-dev.properties
# 开发环境用户图片上传路径
file.imageUserFaceLocation = E:\\workspace\\images\\foodie\\face
file-upload-prod.properties
# 生产环境用户图片上传路径
file.imageUserFaceLocation = /workspace/images/foodie/face
编写一个FileUpload类
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
/**
* @author: xuzhi
* @date: 2021/7/13 13:49
*/
@Component
@ConfigurationProperties(prefix = "file")
@PropertySource("classpath:file-upload-dev.properties")
public class FileUpload {
private String imageUserFaceLocation;
public String getImageUserFaceLocation() {
return imageUserFaceLocation;
}
public void setImageUserFaceLocation(String imageUserFaceLocation) {
this.imageUserFaceLocation = imageUserFaceLocation;
}
}
现在我们可以通过类来获取了。当切换环境的时候,我们修改FileUpload的上注解对应的文件名就行了。
String fileSpace = fileUpload.getImageUserFaceLocation();