如何在Spring中记录.env文件的值

xwbd5t1u  于 2023-11-16  发布在  Spring
关注(0)|答案(1)|浏览(117)

当我在我的主应用程序中记录我的env变量时,我得到了空值。如何解决这个问题?或者有其他检查我的env变量的最佳实践吗?
YAML File

SERVER:
  PORT: ${SERVER_PORT}

spring:
  datasource:
    url: ${DB_URL}
    username: ${USERNAME}
    password: ${PASSWORD}
    driverClassName: ${DRIVER_CLASSNAME}

  jpa:
    spring.jpa.database-platform: ${DB_PLATFORM}

字符串
Env File

SERVER_PORT=8070

DB_URL="jdbc:h2:mem:dcbapp"
DRIVER_CLASSNAME="org.h2.Driver"
DB_PLATFORM="org.hibernate.dialect.H2Dialect"

WELCOME_MESSAGE="Welcome to the Student App"


My Main Application
我尝试使用Logger和@Value(“”)注解进行日志记录,但结果仍然相同
Output软件包com.example.demo;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.logging.Logger;

@SpringBootApplication
public class DemoApplication {
    @Value("${SERVER.PORT}")
    private static String port;



    public static void main(String[] args) {

        SpringApplication.run(DemoApplication.class, args);
        //To display using port variable
        System.out.println("Port: "+ port);
        // To display using System.getenv("PORT")
        System.out.println("Port: "+ System.getenv("PORT"));

    }
}

abithluo

abithluo1#

不幸的是,输出仍然相同.不知道是什么原因,这.
我通过在我的主应用程序中这样做来修复它

public static void main(String[] args) {

        ConfigurableApplicationContext context = SpringApplication.run(DemoApplication.class, args);
        Environment env = context.getEnvironment();

        String port = env.getProperty("server.port");
        if (port != null) {
            System.out.println("Port: " + port);
        } else {
            System.out.println("Port environment variable is not set.");
        }
}

字符串

相关问题