SpringBoot中@ConfigurationProperties使用及乱码问题

常用与注入对象数据

1.加载坐标

  <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

2.解决中文乱码问题

在IDE的settings中设置文件编码
在这里插入图片描述

3.使用@ConfigurationProperties

属性用getter和setter,反射机制

package edu.xiao.controller;

import org.springframework.boot.context.properties.ConfigurationProperties;
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
@ConfigurationProperties(prefix = "person")
public class QuickConfigurationAnnoController {
    private String name;
    private String address;
    private Integer age;

    @RequestMapping("/ConfigurationMethod")
    public @ResponseBody String firstMethod(){
        return "age:"+age+",name:"+name+",address: "+address;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

4.配置文件

推荐使用yml文件格式,在写好属性时有提示

I.application.properties

#服务器端口
server.port=8088
server.servlet.context-path=/demo
person.age = 18
person.name = 张三
person.address = 北京

效果展示

在这里插入图片描述

II.application.yml

写好属性时会有提示功能,但如果properties有该属性的话,则会覆盖
在这里插入图片描述

将properties文件中person属性注释后,在新建application.yml文件

person:
  name: 李四
  age: 22
  address: 湖南
效果

在这里插入图片描述

如果还有中文乱码问题

添加@PropertySource注解,把要读取文件写好,以及encoding
在这里插入图片描述

发布了25 篇原创文章 · 获赞 25 · 访问量 1035

猜你喜欢

转载自blog.csdn.net/Android_Cob/article/details/105577513
今日推荐