使用@value注解配置文件自动映射到属性和实体类
配置文件加载
方式一:
1、Controller控制器类上面配置
@PropertySource({"classpath:resource.properties"})
2、增加属性
@Value("${test.name}")
private String name;
3、代码
application.properties配置文件
web.upload-path=/Users/jack/Desktop
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/test/,file:${web.upload-path}
spring.devtools.restart.trigger-file=trigger.txt
#文件上传路径,Windows为某个磁盘,Linux服务器为某个路径
web.file.path=F:/java-workspace/xdclass_springboot/src/main/resources/static/images/
控制器:postman:http://localhost:8080/apiTempl/uploads 访问
package net.xdclass.demo.controller;
import net.xdclass.demo.domain.FunctionUtil;
import net.xdclass.demo.domain.JsonData;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
/**
* 描述:模板文件显示在浏览器测试
*/
//@Controller
@RestController
@RequestMapping("apiTempl")
//指定配置文件的路径
@PropertySource({"classpath:application.properties"})
public class FileController {
/**
* 上传文件
* @return
*/
//文件存储路径
//private static final String file_path = "F:/java-workspace/xdclass_springboot/src/main/resources/static/images/";
@Value("${web.file.path}")//增加属性
private String file_path;
@PostMapping("uploads")
public JsonData uploadsFile(@RequestParam("head_img") MultipartFile file, HttpServletRequest request){
System.out.println("配置文件注入打印,路径为:"+file_path);
String name = request.getParameter("name");//name信息
System.out.println("用户名:"+name);
//判断文件是否为空
if (file.isEmpty()){
return new JsonData(0,"","文件为空");
}
//判断文件的大小
boolean status = FunctionUtil.checkFileSize(file.getSize(),20,"kb");
if (!status){
return new JsonData(0,"","上传文件大小超出限制");
}
//获取文件名
String fileName = file.getOriginalFilename();
System.out.println("用户名:" + fileName);
//获取图片的后缀,如图片的png,jpg等
String suffixName = fileName.substring(fileName.lastIndexOf("."));
System.out.println("上传文件的后缀:"+suffixName);
String checkStr = ".png,.jpg,.jpeg";
boolean strStatus = checkStr.contains(suffixName);
if (!strStatus){
return new JsonData(0,"","上传文件后缀不一致");
}
//文件上传后的路径
fileName = UUID.randomUUID() + suffixName;
System.out.println("转换后的图片名称:"+fileName);
Date date = new Date();
String filePath = file_path + new SimpleDateFormat("yyyy-MM-dd").format(date);
//如果不存在,创建文件夹
File f = new File(filePath);
if(!f.exists()){
f.mkdirs();
}
System.out.println("上传路径:"+filePath);
File dest = new File(filePath+ "/" + fileName);
try{
file.transferTo(dest);//MultipartFile 对象的transferTo方法,用于文件保存(效率和操作比原先用FileOutStream方便和高效)
return new JsonData(1,fileName,"上传成功");
}catch (IllegalStateException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
return new JsonData(0,"","上传失败");
}
}
方式二:实体类配置文件
步骤:
1、添加 @Component 注解;
2、使用 @PropertySource 注解指定配置文件位置;
3、使用 @ConfigurationProperties 注解,设置相关属性;
4、必须 通过注入IOC对象Resource 进来 , 才能在类中使用获取的配置文件值。
@Autowired
private ServerSettings serverSettings;
例子:
@Configuration
@ConfigurationProperties(prefix="test")
@PropertySource(value="classpath:resource.properties")
public class ServerConstant {}
代码:
1、application.properties配置文件
2、控制器
package net.xdclass.demo.controller;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import net.xdclass.demo.domain.ServerSettings;
import net.xdclass.demo.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
//@RestController返回json格式
@RestController
//定义控制器对应法URL
@RequestMapping("/testGet")
public class GetController {
private Map<String,Object> params = new HashMap<>();
/**
* 测试实体类配置文件
*/
@Autowired
private ServerSettings serverSettings;
@GetMapping("test_properties")
public Object testProperties(){
return serverSettings;
}
}
3、服务器信息配置类===ServerSettings
package net.xdclass.demo.domain;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
/**
* 服务器配置
*/
@Component//注解
//注解指定配置文件位置
@PropertySource({"classpath:application.properties"})
//注解,设置相关属性;@ConfigurationProperties如果不加后面的(prefix="test")
//则ServerSettings的name/domain必须与application.properties(也不加前缀)的名称一致
@ConfigurationProperties(prefix="test")
public class ServerSettings {
private String name;//项目名称
private String domain;//域名
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
}
常见问题:
1、配置文件注入失败,Could not resolve placeholder
解决:根据springboot启动流程,会有自动扫描包没有扫描到相关注解,
默认Spring框架实现会从声明@ComponentScan所在的类的package进行扫描,来自动注入,
因此启动类最好放在根路径下面,或者指定扫描包范围
spring-boot扫描启动类对应的目录和子目录
2、注入bean的方式,属性名称和配置文件里面的key一一对应,就用加@Value 这个注解
如果不一样,就要加@value("${XXX}")