软件编程
位置:首页>> 软件编程>> java编程>> @Value如何获取yml和properties配置参数

@Value如何获取yml和properties配置参数

作者:stay hungry,stay you  发布时间:2021-12-12 13:24:01 

标签:@Value,yml,properties,参数

@Value获取yml和properties配置参数

@Value如何获取yml和properties配置参数

Yml:


#定时任务配置    
application:  
   xxl:
     job:
       enabled: true
       admin:
         addresses: http:///yusp-job-admin/  #127.0.0.1:8080指网关ip:port,yusp-job-admin为调度中心服务名称。通过网关,注册到微服务的/api/server接口,完成注册动作
       executor:          
         appname: af_job   #执行器名称,要求务必唯一
         ip: 10.21.126.237  #执行器IP [选填]:默认为空表示自动获取IP,多网卡时可手动设置指定IP
         port: 9097          #调度中心给微服务发送任务,通过此端口发送指令
         logpath: D:/temp    #执行器日志文件路径
         logretentiondays: 3  # 本地日志保存天数,-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如何获取yml和properties配置参数 @Value如何获取yml和properties配置参数

赋值:

@Value(“true”) 直接赋值

@value注解获取yml文件中的值问题

在类中使用@Value注解获取yml配置文件中的值时,需要注意:

1、yml文件中,当值为0000

这种类型的值时,需要用双引号将值引起来。

比如:

错误:key=0000

正确:key=“0000”

如果不使用双引号的话,在使用@value注解时,得到的值是0,而不是0000

2、使用@Value注解得到的是null

需要使用@Autowired进行注入,对应类需要加上@Service

来源:https://blog.csdn.net/weixin_41987908/article/details/106982035

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com