Spring boot优雅配置文件变量注入
参数说明
- @PropertySource: 配置扫描的文件地址
- @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;
@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
- Global Encoding --> UTF-8
- Project Encoding --> UTF-8
- 打钩 Transparent native-to-ascii conversion
- 配置目录(
resources
)加入到Path
中