Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the value from system property in spring boot

I am using following command to run my spring boot application

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

@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. Do I need to use conditional bean or something?

like image 974
rocky Avatar asked Dec 21 '18 08:12

rocky


People also ask

How do I fetch values from application properties in spring boot?

You can use @Value("${property-name}") from the application. properties if your class is annotated with @Configuration or @Component . You can make use of static method to get the value of the key passed as the parameter. Save this answer.

What is @value annotation is used for?

Spring @Value annotation is used to assign default values to variables and method arguments. We can read spring environment variables as well as system variables using @Value annotation.


1 Answers

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. 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
like image 144
Eslam Nawara Avatar answered Oct 22 '22 10:10

Eslam Nawara