@Value如何獲取yml和properties配置參數(shù)
更新時間:2021年07月07日 08:59:48 作者:stay hungry,stay you
這篇文章主要介紹了@Value如何獲取yml和properties配置參數(shù)的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
@Value獲取yml和properties配置參數(shù)
Yml:
#定時任務(wù)配置 application: xxl: job: enabled: true admin: addresses: http:///yusp-job-admin/ #127.0.0.1:8080指網(wǎng)關(guān)ip:port,yusp-job-admin為調(diào)度中心服務(wù)名稱。通過網(wǎng)關(guān),注冊到微服務(wù)的/api/server接口,完成注冊動作 executor: appname: af_job #執(zhí)行器名稱,要求務(wù)必唯一 ip: 10.21.126.237 #執(zhí)行器IP [選填]:默認為空表示自動獲取IP,多網(wǎng)卡時可手動設(shè)置指定IP port: 9097 #調(diào)度中心給微服務(wù)發(fā)送任務(wù),通過此端口發(fā)送指令 logpath: D:/temp #執(zhí)行器日志文件路徑 logretentiondays: 3 # 本地日志保存天數(shù),-1為永遠保存
package com.xxljob.config; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import cn.com.yusys.yusp.commons.job.core.executor.XxlJobExecutor; @Configuration @ConditionalOnProperty(name = "application.xxl.job.enabled", havingValue = "true", matchIfMissing = false) public class XxlJobAutoConfiguration { private Logger logger = LoggerFactory.getLogger(XxlJobAutoConfiguration.class); @Value("${application.xxl.job.admin.addresses}") private String adminAddresses; @Value("${application.xxl.job.executor.appname}") private String appName; @Value("${application.xxl.job.executor.ip}") private String ip; @Value("${application.xxl.job.executor.port}") private int port; @Value("${application.xxl.job.executor.logpath}") private String logPath; @Value("${application.xxl.job.executor.logretentiondays}") private int logRetentionDays; public XxlJobAutoConfiguration() { } @Bean(initMethod = "start", destroyMethod = "destroy") public XxlJobExecutor xxlJobExecutor() throws IOException { logger.info(">>>>>>>>>>> xxl-job config init."); XxlJobExecutor xxlJobExecutor = new XxlJobExecutor(); xxlJobExecutor.setAdminAddresses(adminAddresses); xxlJobExecutor.setAppName(appName); xxlJobExecutor.setIp(ip); xxlJobExecutor.setPort(port); xxlJobExecutor.setLogPath(logPath); xxlJobExecutor.setLogRetentionDays(logRetentionDays); return xxlJobExecutor; } }
Properties:
賦值:
@Value(“true”) 直接賦值
@value注解獲取yml文件中的值問題
在類中使用@Value注解獲取yml配置文件中的值時,需要注意:
1、yml文件中,當值為0000
這種類型的值時,需要用雙引號將值引起來。
比如:
錯誤:key=0000
正確:key=“0000”
如果不使用雙引號的話,在使用@value注解時,得到的值是0,而不是0000
2、使用@Value注解得到的是null
需要使用@Autowired進行注入,對應(yīng)類需要加上@Service
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Spring定時任務(wù)輪詢本地數(shù)據(jù)庫實現(xiàn)過程解析
這篇文章主要介紹了Spring定時任務(wù)輪詢本地數(shù)據(jù)庫實現(xiàn)過程解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-01-01