从配置文件中读取配置项。
读取springboot
的.yml
配置文件:
xxl:
job:
enabled: true
admin:
addresses: http://127.0.0.1:8080/xxl-job-admin
accessToken:
executor:
appname: ${spring.application.name}
address:
ip:
port: 9999
logpath: /zlogs/${spring.application.name}/xxl-job/jobhandler
logretentiondays: 30
使用两种方式均能读取配置文件中属性值。
@Data
@Configuration
@ConditionalOnProperty(value = "xxl.job.enabled", havingValue = "true")
@ConfigurationProperties(prefix = "xxl.job")
public class XxlJobProperties {
private Admin admin;
private String accessToken;
private Executor executor;
@Data
public static class Admin{
private String addresses;
}
@Data
public static class Executor{
private String appname;
private String address;
private String ip;
private int port;
private String logPath;
private int logRetentionDays;
}
}
@Configuration
@Slf4j
public class XxlJobConfig1 {
@Value("${xxl.job.admin.addresses}")
private String adminAddresses;
@Value("${xxl.job.accessToken}")
private String accessToken;
@Value("${xxl.job.executor.appname}")
private String appname;
@Value("${xxl.job.executor.ip}")
private String ip;
@Value("${xxl.job.executor.port}")
private int port;
@Value("${xxl.job.executor.logpath}")
private String logPath;
@Value("${xxl.job.executor.logretentiondays}")
private int logRetentionDays;
@Bean(initMethod = "start", destroyMethod = "destroy")
public XxlJobExecutor xxlJobExecutor() {
log.info(">>>>>>>>>>> xxl-job config init.");
XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor();
xxlJobSpringExecutor.setAdminAddresses(adminAddresses);
xxlJobSpringExecutor.setAppname(appname);
xxlJobSpringExecutor.setIp(ip);
xxlJobSpringExecutor.setPort(port);
xxlJobSpringExecutor.setAccessToken(accessToken);
xxlJobSpringExecutor.setLogPath(logPath);
xxlJobSpringExecutor.setLogRetentionDays(logRetentionDays);
return xxlJobSpringExecutor;
}
}
如果注释掉配置文件中属性值时:
xxl:
job:
enabled: true
admin:
addresses: http://127.0.0.1:8080/xxl-job-admin
accessToken:
executor:
appname: ${spring.application.name}
address:
# ip:
# port: 9999
logpath: /zlogs/${spring.application.name}/xxl-job/jobhandler
logretentiondays: 30
@ConfigurationProperties读取到ip和port为null,而@Value则会抛出异常。
1、@ConfigurationProperties
读取的属性不存在时,默认将值设置为null
,程序启动不会报错。而@Value
读取的属性不存在时
,程序启动会报错。
2、@Value
有个好处,就是防止我们配置项遗漏。当配置遗漏时,启动程序肯定出错,这样避免了一些因为遗漏配置项导致的BUG。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。