属性配置
配置文件
aal.use.cache=true
aal.appid=ai_c9dc4958d5b2a0ec0f518f7
aal.ip.address=127.0.0.1
属性类
@Component
public class Properties {
public static boolean useCache;
public static String appId;
public static String ipAddress;
// 设置默认值为false 或者 public static boolean useCache = false;
// @Value("${aal.use.cache:false}")
@Value("${aal.use.cache}")
public void setUseCache(boolean useCache) {
CweProperties.useCache = useCache;
}
// 设置默认值为空字符串: @Value("${aal.appid:}") 或者 public static String appId = "";
@Value("${aal.appid}")
public void setAppId(String appId) {
Properties.appId = appId;
}
// 设置默认值为 ipAddress = "127.0.0.1";
@Value("${aal.ip.address:127.0.0.1}")
public void setIpAddress(String ipAddress) {
// 只在初始化的时候赋值, 后续手动操作无效
if (Properties.ipAddress == null) {
Properties.ipAddress = ipAddress;
}
}
}
使用案例
System.out.println(Properties.appId);
System.out.println(Properties.ipAddress);
配置类配置
配置文件
jaemon:
server-id: 10
配置类
@Configuration
@ConfigurationProperties(prefix = "jaemon", ignoreInvalidFields = true)
public class Properties implements InitializingBean {
private static boolean master = true;
// 静态属性
private static int serverId = 0;
public static boolean isMaster() {
return master;
}
public static int getServerId() {
return serverId;
}
// 注入静态配置值
public void setServerId(int serverId) {
Properties.serverId = serverId;
if (serverId != 0) {
Properties.master = false;
}
}
// 配置项校验
@Override
public void afterPropertiesSet() throws Exception {
Assert.state(serverId > -1, "serverId必须大等0");
}
}
实现原理
原理: 通过拿到配置类属性的set方法,然后反射执行set配置类实例的set方法进行属性值注入。
org.springframework.boot.context.properties.bind.JavaBeanBinder