Spring boot優雅配置文件變量注入

Spring boot優雅配置文件變量注入

參數說明

  • @PropertySource: 配置掃描的文件地址
    • classpath: 默認爲resource目錄
  • @ConfigurationProperties: 批量注入配置字段
    • prefix 配置需要注入的配置參數前綴
    • ignoreUnknownFields 是否忽略未知字段
  • @Configuration 標記這個類讓Spring掃描到

java代碼

package com.smart.life.userserver.common;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

/**
 * @Author: WanG
 * @Date: 2020/6/11 16:59
 * @version: v1.0
 * @description: 系統常量配置
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@PropertySource("classpath:smart-life.properties")
@Configuration
@ConfigurationProperties(prefix = "my.constant",
		ignoreUnknownFields = false)
public class SmartLifeConstant {

	private PetClass pet;
	private User user;

	@Data
	public static class User {
		private String name;
		private String gender;

	}

	@Data
	public static class PetClass {
		private String name;
		private String gender;

	}
}

配置文件

smart-life.properties

my.constant.user.name=名字
my.constant.user.gender=性別
my.constant.pet.type=貓咪
my.constant.pet.gender=貓咪性別

效果展示

控制層代碼示例

	@PostMapping("test")
	public ServerReturnResult test(){
		SmartLifeConstant bean = SpringUtils.getBean(SmartLifeConstant.class);
		log.info("用戶-->name:{}({}), 寵物 --> name:{}({})",
				bean.getUser().getName(),
				bean.getUser().getGender(),
				bean.getPet().getName(),
				bean.getPet().getGender());
		return ServerReturnResult.success();
	}

控制檯效果

中文亂碼問題

IDEA

  1. Global Encoding --> UTF-8
  2. Project Encoding --> UTF-8
  3. 打鉤 Transparent native-to-ascii conversion
  4. 配置目錄(resources)加入到Path
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章