1.映射到属性
package top.ytheng.demo.controller; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/file") @PropertySource({"classpath:application.properties"}) public class FileController { @Value("${web.file.path}") private String filePath; @RequestMapping("/testpath") @ResponseBody private Object testPath() { return filePath; } }
2.映射到类
(1)添加类
package top.ytheng.demo.entity; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; @Component //使用该注解时,表示添加前缀,得把@Value注解去掉 //@ConfigurationProperties(prefix="serversettings") @PropertySource({"classpath:application.properties"}) public class ServerSettings { @Value("${serversettings.name}") private String name; @Value("${serversettings.domain}") 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; } }
(2)添加控制器
package top.ytheng.demo.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import top.ytheng.demo.entity.ServerSettings; @RestController public class UserController { @Autowired private ServerSettings serverSettings; @GetMapping("/testproperties") public Object testProperties() { return serverSettings; } }
3.添加application.properties配置文件
#自定义文件上传路径 web.file.path=C:\\Users\\chenchao\\eclipse-workspace\\springboot-demo\\src\\main\\resources\\static\\images\\ #端口号 server.port=8090 #测试实体类配置 serversettings.name=www.spring.io serversettings.domain=springboot
4.添加启动类
package top.ytheng.demo; import javax.servlet.MultipartConfigElement; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.MultipartConfigFactory; @SpringBootApplication //等于下面3个 //@SpringBootConfiguration //@EnableAutoConfiguration //@ComponentScan public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } //文件大小配置 public MultipartConfigElement multipartConfigElement() { MultipartConfigFactory factory = new MultipartConfigFactory(); //单个文件最大 factory.setMaxFileSize("10240KB"); //设置总上传数据总大小 factory.setMaxRequestSize("102400KB"); return factory.createMultipartConfig(); } }
5.测试路径
http://localhost:8090/file/testpath http://localhost:8090/testproperties