簡體   English   中英

Spring Boot環境變量未正確反映

[英]Spring boot environment variable are not reflecting properly

我正在Spring Boot應用程序上工作,在這里我想通過配置服務器動態地完全外部化環境變量。

所以下面是我編寫的代碼。

應用程序

package com.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

@Configuration
@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan("com.myPackage, com.util")
@PropertySource("classpath:application.properties")
public class Application extends SpringBootServletInitializer {

    static final Logger logger = LoggerFactory.getLogger(Application.class);
    public static ApplicationContext ctx;

    public static void main(String[] args) throws Exception {
        logger.info("Application starting....");
        ctx = SpringApplication.run(Application.class, args);
        logger.info("Application started successfully....");

    }

    @Bean
    public static PropertySourcesPlaceholderConfigurer
    propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}

application.properties

server.port=${server.port}    
ENDPOINT_SHAN=${name.mya}

配置服務器:

APPLICATION_NAME=myapp
server.port=8081
name.mya=myName

讀取屬性

import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import com.apptium.Application;

@Component("configurationProperties")
public class ConfigurationProperties {

    private static Environment prop;

    public static String getConfigValue(String key)   {
        String value = null;
        if (prop == null) {
            prop = Application.ctx.getBean(Environment.class);
        }
        if (prop.getProperty(key) != null) {
            value = prop.getProperty(key).trim();
        }
        if (value == null && System.getenv(key) !=null) {
            value = System.getenv(key).trim();
        }
        return value;
    }
}

因此,當我嘗試獲取屬性ENDPOINT_SHAN ,它將返回ENDPOINT_SHAN==${name.mya}但它需要返回ENDPOINT_SHAN==myName

並且也想知道如何正確使用server.port的屬性。

無論如何,我想知道如何獲取ENDPOINT_SHAN的實際屬性。

您說過name.mya是在“配置服務器”中定義的,但是您的代碼未顯示與此服務器建立任何連接。 您需要先從服務器讀取它,然后才能解析${name.mya}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM