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
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章