JAVA Spring Boot:如何访问普通类中的 application.properties 值

Kis*_*nki 4 java class spring-boot

我知道如何访问Java Spring boot 中的类application.properties中的值@Service,如下所示

@Service
public class AmazonClient {

    @Value("${cloud.aws.endpointUrl}")
    private String endpointUrl;
}
Run Code Online (Sandbox Code Playgroud)

但我正在寻找一个选项来直接在任何类中访问该值(没有 @Service 注释的类)

例如

public class AppUtils {
      @Value("${cloud.aws.endpointUrl}")
      private String endpointUrl;
}
Run Code Online (Sandbox Code Playgroud)

但这又回来了null。任何帮助,将不胜感激。我已经读过这里但没有帮助。

Igo*_*lin 9

没有“神奇”的方法可以将属性文件中的值注入到非 bean 的类中。您可以在类中定义一个静态java.util.Properties字段,在加载类时手动从文件中加载值,然后使用该字段:

public final class AppUtils {
    private static final Properties properties;

    static {
        properties = new Properties();

        try {
            ClassLoader classLoader = AppUtils.class.getClassLoader();
            InputStream applicationPropertiesStream = classLoader.getResourceAsStream("application.properties");
            applicationProperties.load(applicationPropertiesStream);
        } catch (Exception e) {
            // process the exception
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 但是,如果您使用“application-<profile>.properties”,其中 Spring 会智能地读取根据加载的配置文件覆盖的属性,那么使用这种方法可能会引入错误。在这个建议的实用程序中,它只会在根“application.properties”文件中查找。 (3认同)

归档时间:

查看次数:

21525 次

最近记录:

1 年,11 月 前