6

我正在使用以下命令来运行我的 Spring Boot 应用程序

java -Dlibrary.system.property=value -jar myapp.jar

目前,我可以通过如下命令访问它

System.getProperty("library.system.property")

但是我需要通过 Spring 中的任何注释来访问它,例如

@value(${library.system.property})

我试着用

    @Value("${library.system.property")
    private String property;

    @Bean
    public SampleProvider getSampleProvider () {
        return SampleProvider.from(property);
    }

但该物业的价值为null。我需要使用条件bean还是什么?

4

4 回答 4

14

您可以使用以下表达式访问系统属性:

@Value("#{systemProperties['library.system.property']}")
private String property

您还可以使用以下表达式访问系统环境:

@Value("#{systemEnvironment['SOME_ENV_VARIABLE']}")
private String property

Lastly, if you are using Spring Boot you can refer to the property name directly as long as you are passing it in the command line. For example, if you launch the JAR like java -jar boot.jar --some.property=value you can read it as:

@Value("${some.property}")
private String property
于 2018-12-21T10:59:33.903 回答
3

谢谢大家。通过更改通过命令行传递参数的方式解决了问题,如下所示

java -jar myapp.jar --library.system.property=value

通过以下代码段访问值

@Value("${library.system.property}")
private String property;

@Bean
public SampleProvider getSampleProvider () {
    return SampleProvider.from(property);
}
于 2018-12-21T09:56:52.003 回答
0

Simply use

import org.springframework.boot.system.SystemProperties;
...
String propertyKey = "library.system.property";
String propertyValue = SystemProperties.get(propertyKey);
于 2020-05-15T11:27:53.760 回答
-2

You can access your data from properties file by using @ Value on your controller. For example: @Value("${library.system.property}") private String property;

Now your value is in property,now you can use it anywhere.

于 2018-12-24T10:55:17.960 回答