开始
头像保存的地址优化
创建一个资源文件。
这样我们就可以把资源的属性写到这里面去。
file-upload-dev.properties
file-upload-dev.properties
我们具体的值包含了File.separator
我们还是只能使用这种方式来替代。如果是windows系统, 那么这里的配置就要改成\workspaecs\images。。。。
这是在windows下的配置
file.imageUserFaceLocation=D:\\demos\\upload
把这个文件复制一份,然后改个名字叫做prod代表生产环境。file-upload-prod.properties
创建resource包
创建类。
让这个java类和资源文件进行关联。首先加上propertySource注解。
import org.springframework.context.annotation.PropertySource;
@PropertySource("classpath:file-upload-dev.properties")
public class FileUpload {
}
定义属性,生成get和set方法
@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;
}
}
加上前缀
加上@Component注解,做为一个组件,让Spring容器扫描。被扫描到,这个文件才能使用。
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@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;
}
}
controller内使用
@Autowired
private FileUpload fileUpload;
这样就可以通过配置文件获取文件保存的路径了。
String fileSpace=fileUpload.getImageUserFaceLocation();
启动服务测试
先maven install
到实际的目录内查看