SpringBoot注解把配置文件自动映射到属性和实体类实战

SpringBoot注解把配置文件自动映射到属性和实体类实战

简介:讲解使用@value注解配置文件自动映射到属性和实体类

1、配置文件加载

方式一

1、Controller上面配置

   @PropertySource({"classpath:resource.properties"})

2、增加属性

@Value("${test.name}")

private String name;

    文件上传修改示例:

    FileController.java:

    

 1 package net.xdclass.demo.controller;
 2 
 3 import java.io.File;
 4 import java.io.IOException;
 5 import java.util.UUID;
 6 
 7 import javax.servlet.http.HttpServletRequest;
 8 
 9 import net.xdclass.demo.domain.JsonData;
10 
11 import org.springframework.beans.factory.annotation.Value;
12 import org.springframework.context.annotation.PropertySource;
13 import org.springframework.stereotype.Controller;
14 import org.springframework.web.bind.annotation.RequestMapping;
15 import org.springframework.web.bind.annotation.RequestParam;
16 import org.springframework.web.bind.annotation.ResponseBody;
17 import org.springframework.web.multipart.MultipartFile;
18 
19 /**
20  * 功能描述:文件测试
21  *
22  * <p> 创建时间:Apr 22, 2018 11:22:29 PM </p> 
23  */
24 @Controller
25 @PropertySource({"classpath:application.properties"})
26 public class FileController {
27 
28     @RequestMapping(value = "/api/v1/gopage")
29     public Object index() {
30         return "index";
31     }
32 
33     //private static final String filePath = "L:/Workspaces/Eclipse_Neon/txkt/SpringBootClass/xdclass_springboot/src/main/resources/static/images/";//末尾需要加/,这样才能写进来
34     //private static final String filePath = "L:/images/";//末尾需要加/,这样才能写进来
35     
36     @Value("${web.file.path}")
37     private String filePath;
38 
39     @RequestMapping(value = "upload")
40     @ResponseBody
41     public JsonData upload(@RequestParam("head_img") MultipartFile file, HttpServletRequest request) {
42 
43         // file.isEmpty(); 判断图片是否为空
44         // file.getSize(); 图片大小进行判断
45 
46         System.out.println("配置注入打印,文件路径为:" + filePath);
47         
48         String name = request.getParameter("name");
49         System.out.println("用户名:" + name);
50 
51         // 获取文件名
52         String fileName = file.getOriginalFilename();
53         System.out.println("上传的文件名为:" + fileName);
54 
55         // 获取文件的后缀名,比如图片的jpeg,png
56         String suffixName = fileName.substring(fileName.lastIndexOf("."));
57         System.out.println("上传的后缀名为:" + suffixName);
58 
59         // 文件上传后的路径
60         fileName = UUID.randomUUID() + suffixName;
61         System.out.println("转换后的名称:" + fileName);
62 
63         File dest = new File(filePath + fileName);
64 
65         try {
66             file.transferTo(dest);
67 
68             return new JsonData(0, fileName);
69         } catch (IllegalStateException e) {
70             e.printStackTrace();
71         } catch (IOException e) {
72             e.printStackTrace();
73         }
74         return new JsonData(-1, "fail to save ", null);
75     }
76 
77 }

    application.properties:

 1 web.images-path=L:/images
 2 spring.resources.static-locations = classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/test/,file:${web.upload-path}
 3 #指定某些文件不进行监听,即不会进行热加载devtool(重启后不会监听下面这个文件)
 4 #spring.devtools.restart.exclude=application.properties
 5 
 6 #通过触发器,去控制什么时候进行热加载部署新的文件
 7 spring.devtools.restart.trigger-file=trigger.txt
 8 
 9 server.port=8083
10 
11 #文件上传路径配置
12 web.file.path=L:/images
13 
14 #测试配置文件注入
15 test.name=www.xdclass.net
16 test.domain=springboot

    控制台结果:

      配置注入打印,文件路径为:L:/images

      用户名:123

      上传的文件名为:hongmi6.jpg

      上传的后缀名为:.jpg

      转换后的名称:ee4b60bd-35b4-4df6-bee6-ed62dd5e4a00.jpg

    浏览器返回值:

    {"code":0,"data":"ee4b60bd-35b4-4df6-bee6-ed62dd5e4a00.jpg","msg":null}

    方式二:实体类配置文件
步骤:

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 {

        代码示例:

        ServerSettings.java:

 1 package net.xdclass.demo.domain;
 2 
 3 import org.springframework.boot.context.properties.ConfigurationProperties;
 4 import org.springframework.context.annotation.PropertySource;
 5 import org.springframework.stereotype.Component;
 6 
 7 //服务器配置
 8 @Component
 9 @PropertySource({"classpath:application.properties"})
10 //@ConfigurationProperties
11 //自动加入前缀,无需写入test.
12 @ConfigurationProperties(prefix="test")
13 //若不想使用prefix="test",前提是该类中定义的名称要与application.properties中定义的名称一致,即一一对应
14 public class ServerSettings {
15 
16     //名称
17     //使用prefix="test"后,无需再使用Value注解
18     //@Value("${name}")
19     private String name;
20     
21     //域名地址
22     //@Value("${domain}")
23     private String domain;
24 
25     public String getName() {
26         return name;
27     }
28 
29     public void setName(String name) {
30         this.name = name;
31     }
32 
33     public String getDomain() {
34         return domain;
35     }
36 
37     public void setDomain(String domain) {
38         this.domain = domain;
39     } 
40     
41     
42 }

      application.properties同上一个示例

      GetController.java部分代码:

1     @Autowired
2     private ServerSettings serverSettings;
3     @GetMapping("/v1/test_properties")
4     public Object testProperties(){
5         return serverSettings;    
6     }

    浏览器测试:

    地址栏输入:http://localhost:8083/v1/test_properties

    结果:{"name":"www.xdclass.net","domain":"springboot"}

常见问题:

1、配置文件注入失败,Could not resolve placeholder

解决:根据springboot启动流程,会有自动扫描包没有扫描到相关注解, 

默认Spring框架实现会从声明@ComponentScan所在的类的package进行扫描,来自动注入,

因此启动类最好放在根路径下面,或者指定扫描包范围

spring-boot扫描启动类对应的目录和子目录

2、注入bean的方式,属性名称和配置文件里面的key一一对应,就不用加@Value 这个注解

如果不一样,就要加@value("${XXX}") 

3、SpringBoot注解把配置文件自动映射到属性和实体类实战简介:讲解使用@value注解配置文件自动映射到属性和实体类1、配置文件加载方式一1、Controller上面配置   @PropertySource({"classpath:resource.properties"})2、增加属性 @Value("${test.name}") private String name;
方式二:实体类配置文件步骤: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、配置文件注入失败,Could not resolve placeholder解决:根据springboot启动流程,会有自动扫描包没有扫描到相关注解, 默认Spring框架实现会从声明@ComponentScan所在的类的package进行扫描,来自动注入,因此启动类最好放在根路径下面,或者指定扫描包范围spring-boot扫描启动类对应的目录和子目录2、注入bean的方式,属性名称和配置文件里面的key一一对应,就用加@Value 这个注解如果不一样,就要加@value("${XXX}")

原文地址:https://www.cnblogs.com/116970u/p/10221268.html