spring boot自定义配置项
配置文件
在application.properties文件添加需要的配置
比如:
file.path=d:\\flies\\springboot\\
@configurationproperties 注解
使用注解@configurationproperties将配置项和实体bean关联起来
实现配置项和实体类字段的关联,读取配置文件数据
import lombok.data;
import org.springframework.boot.context.properties.configurationproperties;
import org.springframework.stereotype.component;
@data
@component
@configurationproperties(prefix = "file")
public class fileconfig {
private string path;
}使用
获取配置信息
fileconfig fileconfig = new fileconfig(); // 文件保存目录 string filepath = fileconfig.getpath();
@postmapping("/upload/")
@responsebody
public response upload(multipartfile file) {
// 验证是否有文件
if(file == null || file.isempty()){
return response.newfail("upload failed, please select file",400);
}
fileconfig fileconfig = new fileconfig();
// 文件保存目录
string filepath = fileconfig.getpath();
// 验证文件夹
file folder = new file(filepath);
if (!folder.exists()) {
folder.mkdirs();
}
// 文件名
string filename = uuid.randomuuid() + file.getoriginalfilename();
filepath = filepath + filename;
file savefile = new file(filepath);
try {
file.transferto(savefile);
return response.newsuccess("upload successful");
} catch (ioexception e) {
e.printstacktrace();
return response.newfail("upload failed",50001);
}
}总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论