简体   繁体   English

如何在 spring 引导中从系统属性中获取值

[英]How to get the value from system property in spring boot

I am using following command to run my spring boot application我正在使用以下命令运行我的 spring 启动应用程序

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

Currently, I am able to access it via following command like below目前,我可以通过如下命令访问它

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

However I need to access it via any annotation in Spring something like但是我需要通过 Spring 中的任何注释来访问它,比如

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

I tried to use我试着用

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

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

But the value of the property is null .但是该属性的值为null Do I need to use conditional bean or something?我需要使用条件 bean 还是什么?

You can access the system properties using the following expression:您可以使用以下表达式访问系统属性:

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

You can also access the system environment using the following expression:您还可以使用以下表达式访问系统环境:

@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.最后,如果您使用的是 Spring Boot,只要您在命令行中传递它,就可以直接引用属性名称。 For example, if you launch the JAR like java -jar boot.jar --some.property=value you can read it as:例如,如果您像java -jar boot.jar --some.property=value这样启动 JAR,您可以将其读作:

@Value("${some.property}")
private String property

Thanks all.谢谢大家。 Issue got resolved by changing the way of passing the argument through command line as below通过更改通过命令行传递参数的方式解决了问题,如下所示

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

Accessing the value by below code snippet通过以下代码片段访问值

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

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

Simply use只需使用

import org.springframework.boot.system.SystemProperties;
...
String propertyKey = "library.system.property";
String propertyValue = SystemProperties.get(propertyKey);
@Configuration
Public class YourAppConfig {

    @Value("${your.system.property}") String prop
    @Autowired
    Public void LoadProperties() {
        System.setProperty(PROPERTY_NAME, prop) ;
    }

    @Bean
    ...

You can access your data from properties file by using @ Value on your controller.您可以通过在控制器上使用 @Value 来访问属性文件中的数据。 For example: @Value("${library.system.property}") private String property;例如:@Value("${library.system.property}") 私有字符串属性;

Now your value is in property,now you can use it anywhere.现在您的价值在于财产,现在您可以在任何地方使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM