How to set arbitrary system.property from Spring Boot? - spring

If I run my app as java jar -Dsomething=anything thejar.jar then I have set a system property.
Can I do that via Spring Boot Configuration files or is my only option to defined a #Configuration class that reads a property and then sets the system property from that?

Spring configuration is highly flexible and provides a hierarchy for resolving configuration properties. You can set properties using the spring config server, environment variables (my preferred approach), system properties, application.yaml/propteries, etc. Check out the docs on externalized configuration
Say you wanted to set a property: app.some.property=foo. You can access this property from any bean using the value annotation:
#Value("${app.some.property}")
private String someProperty;
And then you can set it at runtime using one of the approaches defined above:
1. System Property
java -jar -Dapp.some.property=foo thejar.jar
2. Environment Variable
export APP_SOME_PROPERTY="foo"
java -jar thejar.jar

Related

How to set logging.file.name through command line arguments in spring boot?

I am setting the logging.file.name in application.properties file which I want to pass as command line argument. Is it possible?
The reason is I am trying to run multiple jar files from a single application and I want to display logs of each application run at a single location.
Spring Boot provides several options to externalize configuration.
Spring Boot uses a very particular PropertySource order that is
designed to allow sensible overriding of values. Properties are
considered in the following order (with values from lower items
overriding earlier ones):
Default properties (specified by setting SpringApplication.setDefaultProperties).
#PropertySource annotations on your #Configuration classes. Please note that such property sources are not added to the
Environment until the application context is being refreshed. This is
too late to configure certain properties such as logging.* and
spring.main.* which are read before refresh begins.
Config data (such as application.properties files).
A RandomValuePropertySource that has properties only in random.*.
OS environment variables.
Java System properties (System.getProperties()).
JNDI attributes from java:comp/env.
ServletContext init parameters.
ServletConfig init parameters.
Properties from SPRING_APPLICATION_JSON (inline JSON embedded in an environment variable or system property).
Command line arguments.
properties attribute on your tests. Available on #SpringBootTest and the test annotations for testing a particular
slice of your application.
#TestPropertySource annotations on your tests.
Devtools global settings properties in the $HOME/.config/spring-boot directory when devtools is active.
So you should be possible to override the values defined in your application.properties by setting environment variables, Java system properties, or command line arguments:
Environmant variables: export LOGGING_FILE_NAME=yourfile.txt
Java system property: -Dlogging.file.name=yourfile.txt
Command line argument: --logging.file.name=yourfile.txt

Set application.properties value from JNDI Environment value

I am building a spring boot application, that has RabbitMQ configuration like below.
spring.rabbitmq.host=host
spring.rabbitmq.port=5672
spring.rabbitmq.username=userName
spring.rabbitmq.password=password
I need to set environment specific configuration. But that configuration needs to be read from tomcat context.xml file.
I would need to pass the values for host, username, and password by reading from tomcat Environment tag set in context.xml.
How can I do this?
Spring docs says: 24.3 Application Property Files
If your application runs in a container, then JNDI properties (in java:comp/env) or servlet context initialization parameters can be used instead of, or as well as, environment variables or system properties.
can they be directly used like this:
spring.rabbitmq.host="${rabbitMQHost}"
spring.rabbitmq.port=5672
spring.rabbitmq.username=${rabbitMQUserName}
spring.rabbitmq.password=${rabbitMQPassword}

spring boot YAML default and environment variable override like HOCON files

Is there a way in spring-boot YAML file to do the same as in HOCON files where you can have a default and be able to override it with an environment variable like this:
basedir = "/whatever/whatever"
basedir = ${?FORCED_BASEDIR}
In this case in HOCON if you don't define a environment variable named FORCED_BASEDIR then basedir will be "/whatever/whatever" but if you do then the value of basedir will be whatever is defined in the environment variable.
Thanks
So based on webdizz answer below I looked up a little bit and I found a pretty good description in book "Spring Boot in Action". Here is the hierarchy:
There are, in fact, several ways to set properties for a Spring Boot application. Spring
Boot will draw properties from several property sources, including the following:
Command-line arguments
JNDI attributes from java:comp/env
JVM system properties
Operating system environment variables
Randomly generated values for properties prefixed with random.* (referenced
when setting other properties, such as `${random.long})
An application.properties or application.yml file outside of the application
Licensed to Thomas Snead 58 CHAPTER 3 Customizing configuration
An application.properties or application.yml file packaged inside of the
application
Property sources specified by #PropertySource
Default properties
Spring Boot provides means to define variables at many levels and your case is supported, you just need to define variable in following way:
in application.yml:
basedir: "/whatever/whatever"
and in environment:
export BASEDIR = "/another/whatever"
Then in runtime application will use value from environment.
For more details check this out enter link description here.

Spring boot - expose common application properties with different names

I have a requirement where I need my custom application properties to act as aliases to various common application properties that spring provides for different packages.
Example:
Whenever I set a value to the application property foo.host, it should set the value for spring.rabbit.host property.
Similarly setting the value for foo.port should set the value for spring.rabbitmq.port.
Can this be achieved?
It can, you can add these to your application.properties:
spring.rabbit.host=${foo.host}
spring.rabbit.port=${foo.port}
However, if you still provide spring.rabbit.host via system properties, as an environment variable or as direct argument then it will take precedence over foo config.

Set/override Spring / Spring Boot properties at runtime

At the project with Spring Boot we use application.properties but need to configure some of these properties (like port number of logging level) based on an external configuration. We access the configuration via API so it is known only at runtime.
Is there a way to override or set some Spring properties at runtime (for example using a bean) and if yes how can this be achieved?
You could do this with Spring Cloud Config
Just for the purpose of illustration, here's a relatively quick way to see dynamic property overrides at runtime:
First, for your bean to be able to pick up changed properties, you need to annotate it with
#RefreshScope
Add the spring cloud dependency to your spring boot app, eg for gradle
compile group: 'org.springframework.cloud', name: 'spring-cloud-starter', version: '1.1.1.RELEASE'
( NB You also need the spring boot actuator dependency.)
With the app running, you can view your current config at eg
http://localhost:8080/env
eg if you have a property 'my.property' in application.properties, you'll see something like:
"applicationConfig: [classpath:/application.properties]": {
"my.property": "value1",
etc
To change the value, POST my.property=value2 to /env as application/x-www-form-urlencoded
eg
curl -X POST http://localhost:8080 -d my.property=value2
GET /env again and you'll see the new value appears under the "manager" section
To apply the changed properties, do an empty POST to /refresh. Now your bean will have the new value.
Could you use system properties to pass in the variable? If you configure the PropertyPlaceholderConfigurer you can set the precedence of system properties vs file properties.
For example, something like:
#Bean public PropertyPlaceholderConfigurer placeHolderConfigurer() {
PropertyPlaceholderConfigurer props = new PropertyPlaceholderConfigurer()
props.setSystemPropertiesMode( PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_OVERRIDE )
props.setLocations(new
PathMatchingResourcePatternResolver().getResources("classpath:/**.properties"));
props
}
The above would load your .properties file, but we set the priority to be system variables first, so if you set a system variable that will override the same variable in the config.
Alternatively, looking at the docs, Spring recommends defining a search order in your Environment:
[PropertyPlaceholderConfigurer is still appropriate for use when]
existing configuration makes use of the "systemPropertiesMode" and/or "systemPropertiesModeName" properties. Users are encouraged to
move away from using these settings, and rather configure property
source search order through the container's Environment; however,
exact preservation of functionality may be maintained by continuing to
use PropertyPlaceholderConfigurer.
Hopefully one of the above should sort out what you need?

Resources