Spring引导环境变量没有正确反映

问题描述 投票:0回答:1

我正在开发Spring启动应用程序,我希望通过配置服务器动态地完全外部化我的环境变量。

以下是我编写的代码。

application.Java

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的实际房产。

java spring spring-mvc spring-boot spring-profiles
1个回答
0
投票

您说name.mya是在“配置服务器”中定义的,但您的代码未显示与此服务器建立的任何连接。在${name.mya}变得可解析之前,您需要从服务器读取它。

© www.soinside.com 2019 - 2024. All rights reserved.