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

时间:2022-09-22 20:49:00

@Value获取yml和properties配置参数

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

Yml:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
#定时任务配置   
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为永远保存
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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