Read properties file parameters in config-server to solve the problem that @Value cannot be read

Read the parameters of the common class:
Insert picture description here

Description: Because config-server is used, the configuration file is not in the project but bootstrap.yml is used instead. The real configuration file is on the remote git, so if you use the above method to get it, you will get an error. You can use the following methods to solve it. The reason I personally think is that after the file is placed in git, the project cannot obtain the response file parameters through bootstrap.yml, resulting in a red report

Solution: Let this class implement the EnvironmentAware interface and override the setEnvironment(Environment environment) method to obtain parameter value information from the environment, as follows

Parameter file on git:
Insert picture description here

Project code:

package com.luntek.certificate.config;


import lombok.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

/**
 * @description: elasticsearch相关参数配置
 * @author: Czw
 * @create: 2020-06-29 14:02
 **/
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Configuration
public class EsEnvironmentProperties implements EnvironmentAware {
    
    
    private Environment environment;
    /**
     * ES请求地址
     */
    private String host;

    /**
     * 端口
     */
    private int port;

    /**
     * 协议
     */
    private String protocol;

    @Override
    public void setEnvironment(Environment environment) {
    
    
        this.environment = environment;
        this.host = this.environment.getProperty("es.host");
        String property = this.environment.getProperty("es.port");
        this.port = Integer.parseInt(StringUtils.isEmpty(property) ? "0" : property);
        this.host = this.environment.getProperty("es.host");
        System.err.println("port=" + port);
    }

}

effect:
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_42910468/article/details/107021610