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
在这里插入图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

这次最后一次熬夜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值