我如何从 Java class 中的应用程序-test.properties 文件中获取 属性?

How can i fetch property from application-test.properties file in Java class?

我已经在我的环境中将变量“spring.profiles.active”设置为“test”并且我的 src/main/resources.

中有以下文件

申请-test.properties

它有一台属性“机器”

machineName=mumbai

我想在我的一个基于 Java 的 class 中访问这个 属性。

package com.test.service;

@Component
@RequiredArgsConstructor
public class TestMachine {

    @Value("${machineName}")
    private String machineName;

    @Override
    public void checkMachine() {
        System.out.println(machineName);
    }
}

PropertiesConfig class:

@Configuration
public class PropertiesUtils {

    public static void initProperties() {
        String activeProfile = System.getProperty("spring.profiles.active");
        if (activeProfile == null) {
            activeProfile = "test";
        }
        PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
        Resource[] resources = new ClassPathResource[] {new ClassPathResource("application.properties"),
                        new ClassPathResource("application-" + activeProfile + ".properties")};
        propertySourcesPlaceholderConfigurer.setLocations(resources);
    }
}

但是 运行 这作为 Eclipse 中的 Spring 启动应用程序。我遇到以下错误:

Error creating bean with name 'TestMachine': Injection of autowired dependencies failed;

Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'machineName' in value "${machineName}" at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:180) ~[spring-core-5.3.9.jar:5.3.9]

我错过了什么?我只在大多数网站上找到这种方式。

在 Eclipse 中,您在 Run Configurations.

中设置了 spring.profiles.active 环境变量

只需转至 Run -> Run Configurations... 和 select 选项卡 Environment。添加值为 test.

spring.profiles.active 环境变量

为了给您更好的答案,请显示您的 application.properties 和完整的堆栈跟踪,但这可能会有所帮助。

您可以使用 Environment class.

获取当前配置文件
package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import org.springframework.core.env.Environment;

@SpringBootApplication
public class DemoApplication {

  @Autowired
  Environment env;

  public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);
  }

  @Bean
  public CommandLineRunner run() {
    return new CommandLineRunner() {

      @Override
      public void run(String... args) {
        for (var  p: env.getActiveProfiles()) {
          System.out.println(p);
        }
      }

    };
  }
}

并通过 cli 传递配置文件

使用这个

mvn spring-bot:run -Dspring-boot.run.profiles=test

gradle bootRun --args "'--spring.profiles.active=test'"

java -jar *.jar -Dspring.profiles.active=test