Read Environment Variable in Properties File Spring Boot
24. Externalized Configuration
Leap Kicking allows yous to externalize your configuration so you tin can work with the same application code in unlike environments. Y'all can use backdrop files, YAML files, environment variables and command-line arguments to externalize configuration. Belongings values can be injected directly into your beans using the @Value notation, accessed via Jump's Environs abstraction or bound to structured objects via @ConfigurationProperties.
Leap Kicking uses a very particular PropertySource club that is designed to allow sensible overriding of values. Backdrop are considered in the following lodge:
- Devtools global settings properties on your habitation directory (
~/.spring-boot-devtools.backdropwhen devtools is active). -
@TestPropertySourceannotations on your tests. -
@SpringBootTest#backdropannotation aspect on your tests. - Control line arguments.
- Properties from
SPRING_APPLICATION_JSON(inline JSON embedded in an environment variable or system holding) -
ServletConfiginit parameters. -
ServletContextinit parameters. - JNDI attributes from
java:comp/env. - Java System properties (
System.getProperties()). - Bone environment variables.
- A
RandomValuePropertySourcethat only has properties inrandom.*. - Profile-specific awarding backdrop outside of your packaged jar (
application-{contour}.propertiesand YAML variants) - Profile-specific awarding backdrop packaged inside your jar (
application-{profile}.propertiesand YAML variants) - Application backdrop outside of your packaged jar (
application.propertiesand YAML variants). - Application properties packaged inside your jar (
application.backdropand YAML variants). -
@PropertySourceannotations on your@Configurationclasses. - Default properties (specified using
SpringApplication.setDefaultProperties).
To provide a concrete example, suppose you develop a @Component that uses a name property:
import org.springframework.stereotype.* import org.springframework.beans.factory.note.* @Component public class MyBean { @Value("${proper name}") private String name; }
On your application classpath (e.chiliad. inside your jar) you tin have an awarding.properties that provides a sensible default property value for name. When running in a new environment, an application.properties can be provided exterior of your jar that overrides the proper name; and for i-off testing, yous can launch with a specific command line switch (east.k. java -jar app.jar --name="Leap").
| Tip |
|---|---|
| The $ SPRING_APPLICATION_JSON='{"foo":{"bar":"spam"}}' java -jar myapp.jar In this instance yous will cease up with $ java -Dspring.application.json='{"foo":"bar"}' -jar myapp.jar or control line argument: $ coffee -jar myapp.jar --spring.application.json='{"foo":"bar"}' or as a JNDI variable |
24.1 Configuring random values
The RandomValuePropertySource is useful for injecting random values (e.yard. into secrets or test cases). It can produce integers, longs, uuids or strings, e.g.
my.secret=${random.value} my.number=${random.int} my.bignumber=${random.long} my.uuid=${random.uuid} my.number.less.than.10=${random.int(10)} my.number.in.range=${random.int[1024,65536]}
The random.int* syntax is OPEN value (,max) Close where the Open up,Shut are whatever character and value,max are integers. If max is provided and so value is the minimum value and max is the maximum (sectional).
24.2 Accessing command line backdrop
By default SpringApplication will convert any control line option arguments (starting with '--', east.g. --server.port=9000) to a holding and add together it to the Spring Surroundings. Every bit mentioned above, command line properties ever accept precedence over other property sources.
If you lot don't want control line backdrop to be added to the Environment you lot can disable them using SpringApplication.setAddCommandLineProperties(false).
24.iii Application holding files
SpringApplication will load properties from application.backdrop files in the following locations and add them to the Spring Environment:
- A
/configsubdirectory of the current directory. - The current directory
- A classpath
/configpackage - The classpath root
The listing is ordered past precedence (backdrop defined in locations higher in the list override those defined in lower locations).
If yous don't like application.properties every bit the configuration file name y'all tin can switch to some other by specifying a jump.config.name environment property. You tin can besides refer to an explicit location using the leap.config.location environment property (comma-separated list of directory locations, or file paths).
$ java -jar myproject.jar --leap.config.name=myproject
or
$ java -jar myproject.jar --spring.config.location=classpath:/default.backdrop,classpath:/override.properties
| Warning |
|---|---|
| |
If spring.config.location contains directories (every bit opposed to files) they should end in / (and volition be appended with the names generated from spring.config.proper noun before being loaded, including profile-specific file names). Files specified in spring.config.location are used equally-is, with no back up for profile-specific variants, and volition be overridden past whatsoever profile-specific properties.
Config locations are searched in reverse order. By default, the configured locations are classpath:/,classpath:/config/,file:./,file:./config/. The resulting search order is:
-
file:./config/ -
file:./ -
classpath:/config/ -
classpath:/
When custom config locations are configured, they are used in addition to the default locations. Custom locations are searched before the default locations. For instance, if custom locations classpath:/custom-config/,file:./custom-config/ are configured, the search society becomes:
-
file:./custom-config/ -
classpath:custom-config/ -
file:./config/ -
file:./ -
classpath:/config/ -
classpath:/
This search ordering allows you to specify default values in one configuration file and then selectively override those values in some other. You can provide default values for y'all application in application.properties (or whatsoever other basename you lot choose with bound.config.proper noun) in ane of the default locations. These default values can so be overriden at runtime with a different file located in ane of the custom locations.
| Note |
|---|---|
| If you use surroundings variables rather than system backdrop, most operating systems disallow period-separated key names, merely you can utilise underscores instead (eastward.g. |
| Annotation |
|---|---|
| If you are running in a container and then JNDI properties (in |
24.iv Profile-specific properties
In addition to application.properties files, profile-specific properties tin can also be defined using the naming convention awarding-{profile}.backdrop. The Environs has a set of default profiles (by default [default]) which are used if no active profiles are fix (i.e. if no profiles are explicitly activated so properties from application-default.backdrop are loaded).
Profile-specific backdrop are loaded from the same locations every bit standard application.properties, with profile-specific files always overriding the non-specific ones irrespective of whether the profile-specific files are inside or outside your packaged jar.
If several profiles are specified, a last wins strategy applies. For example, profiles specified by the jump.profiles.active property are added after those configured via the SpringApplication API and therefore take precedence.
| Note |
|---|---|
| If you have specified whatsoever files in |
24.five Placeholders in properties
The values in application.properties are filtered through the existing Environs when they are used so you tin can refer dorsum to previously defined values (e.g. from System properties).
app.name=MyApp app.description=${app.proper noun} is a Bound Boot application
24.six Using YAML instead of Backdrop
YAML is a superset of JSON, and as such is a very convenient format for specifying hierarchical configuration data. The SpringApplication class will automatically support YAML as an alternative to backdrop whenever y'all have the SnakeYAML library on your classpath.
| Note |
|---|---|
| If yous use 'Starters' SnakeYAML will be automatically provided via |
24.6.i Loading YAML
Jump Framework provides two convenient classes that can exist used to load YAML documents. The YamlPropertiesFactoryBean will load YAML as Properties and the YamlMapFactoryBean volition load YAML as a Map.
For case, the following YAML document:
environments: dev: url: http://dev.bar.com proper noun: Developer Setup prod: url: http://foo.bar.com name: My Cool App
Would be transformed into these properties:
environments.dev.url=http://dev.bar.com environments.dev.name=Developer Setup environments.prod.url=http://foo.bar.com environments.prod.name=My Cool App
YAML lists are represented every bit holding keys with [alphabetize] dereferencers, for example this YAML:
my: servers: - dev.bar.com - foo.bar.com
Would be transformed into these properties:
my.servers[0]=dev.bar.com my.servers[1]=foo.bar.com
To bind to properties like that using the Spring DataBinder utilities (which is what @ConfigurationProperties does) yous need to have a property in the target edible bean of type java.util.List (or Set) and you lot either need to provide a setter, or initialize it with a mutable value, e.g. this will demark to the backdrop higher up
@ConfigurationProperties(prefix="my") public class Config { private Listing<String> servers = new ArrayList<Cord>(); public List<String> getServers() { render this.servers; } }
| Note |
|---|---|
| Extra care is required when configuring lists that way as overriding will not piece of work as y'all would expect. In the example above, when my: servers: dev.bar.com,foo.bar.com |
24.vi.2 Exposing YAML as properties in the Spring Environment
The YamlPropertySourceLoader class tin be used to expose YAML as a PropertySource in the Leap Environment. This allows you to utilize the familiar @Value annotation with placeholders syntax to access YAML properties.
24.half dozen.3 Multi-profile YAML documents
You lot can specify multiple profile-specific YAML documents in a single file by using a spring.profiles key to indicate when the certificate applies. For example:
server: address: 192.168.one.100 spring: profiles: development server: address: 127.0.0.1 bound: profiles: production server: address: 192.168.1.120
In the case higher up, the server.address property will be 127.0.0.1 if the development profile is active. If the evolution and product profiles are non enabled, then the value for the property will be 192.168.one.100.
The default profiles are activated if none are explicitly active when the application context starts. So in this YAML nosotros set a value for security.user.countersign that is only available in the "default" contour:
server: port: 8000 spring: profiles: default security: user: countersign: weak
whereas in this example, the password is always fix because it isn't attached to any contour, and it would have to be explicitly reset in all other profiles as necessary:
server: port: 8000 security: user: password: weak
Spring profiles designated using the "spring.profiles" chemical element may optionally exist negated using the ! character. If both negated and not-negated profiles are specified for a single certificate, at least one non-negated profile must match and no negated profiles may match.
24.six.4 YAML shortcomings
YAML files tin't be loaded via the @PropertySource annotation. So in the case that you demand to load values that manner, yous need to use a properties file.
24.6.five Merging YAML lists
As we have seen to a higher place, whatsoever YAML content is ultimately transformed to properties. That process may exist counter intuitive when overriding "list" properties via a profile.
For case, assume a MyPojo object with proper noun and description attributes that are null by default. Let's expose a list of MyPojo from FooProperties:
@ConfigurationProperties("foo") public class FooProperties { private last Listing<MyPojo> list = new ArrayList<>(); public List<MyPojo> getList() { return this.list; } }
Consider the following configuration:
foo: list: - name: my name description: my clarification spring: profiles: dev foo: listing: - name: my another name
If the dev profile isn't active, FooProperties.listing will comprise i MyPojo entry equally defined above. If the dev profile is enabled notwithstanding, the list will still merely contain one entry (with proper name "my another name" and description null). This configuration will not add together a second MyPojo instance to the list, and it won't merge the items.
When a collection is specified in multiple profiles, the one with highest priority is used (and only that one):
foo: list: - name: my proper name clarification: my description - name: another name description: another description spring: profiles: dev foo: list: - name: my another name
In the example to a higher place, considering that the dev profile is active, FooProperties.list will incorporate one MyPojo entry (with name "my another name" and description nil).
24.7 Type-condom Configuration Properties
Using the @Value("${holding}") annotation to inject configuration backdrop can sometimes exist cumbersome, especially if you are working with multiple properties or your data is hierarchical in nature. Spring Boot provides an alternative method of working with properties that allows strongly typed beans to govern and validate the configuration of your application.
package com.example; import java.net.InetAddress; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties("foo") public class FooProperties { individual boolean enabled; private InetAddress remoteAddress; private concluding Security security = new Security(); public boolean isEnabled() { ... } public void setEnabled(boolean enabled) { ... } public InetAddress getRemoteAddress() { ... } public void setRemoteAddress(InetAddress remoteAddress) { ... } public Security getSecurity() { ... } public static class Security { private Cord username; private Cord password; individual List<String> roles = new ArrayList<>(Collections.singleton("USER")); public Cord getUsername() { ... } public void setUsername(Cord username) { ... } public String getPassword() { ... } public void setPassword(String password) { ... } public List<Cord> getRoles() { ... } public void setRoles(Listing<String> roles) { ... } } }
The POJO above defines the following properties:
-
foo.enabled,falseby default -
foo.remote-address, with a type that can be coerced fromString -
foo.security.username, with a nested "security" whose proper noun is adamant past the proper name of the property. In particular the return type is not used at all at that place and could take beenSecurityProperties -
foo.security.countersign -
foo.security.roles, with a collection ofString
| Note |
|---|---|
| Getters and setters are usually mandatory, since binding is via standard Coffee Beans property descriptors, simply like in Spring MVC. At that place are cases where a setter may be omitted:
Some people apply Project Lombok to add getters and setters automatically. Make sure that Lombok doesn't generate any particular constructor for such type every bit it will be used automatically past the container to instantiate the object. |
You also need to list the properties classes to register in the @EnableConfigurationProperties annotation:
@Configuration @EnableConfigurationProperties(FooProperties.class) public class MyConfiguration { }
| Annotation |
|---|---|
| When The bean name in the example above will be |
Fifty-fifty if the configuration above will create a regular bean for FooProperties, we recommend that @ConfigurationProperties only deal with the environment and in particular does not inject other beans from the context. Having said that, The @EnableConfigurationProperties annotation is also automatically applied to your projection so that any existing edible bean annotated with @ConfigurationProperties will exist configured from the Environment. You could shortcut MyConfiguration in a higher place past making certain FooProperties is a already a bean:
@Component @ConfigurationProperties(prefix="foo") public grade FooProperties { }
This style of configuration works particularly well with the SpringApplication external YAML configuration:
foo: remote-address: 192.168.1.1 security: username: foo roles: - USER - ADMIN
To work with @ConfigurationProperties beans you tin can just inject them in the same way equally any other edible bean.
@Service public class MyService { private final FooProperties properties; @Autowired public MyService(FooProperties backdrop) { this.backdrop = backdrop; } @PostConstruct public void openConnection() { Server server = new Server(this.properties.getRemoteAddress()); } }
| Tip |
|---|---|
| Using |
24.vii.one 3rd-political party configuration
Likewise equally using @ConfigurationProperties to comment a class, you can also use it on public @Bean methods. This tin be specially useful when you want to bind properties to tertiary-party components that are exterior of your command.
To configure a bean from the Environment properties, add @ConfigurationProperties to its bean registration:
@ConfigurationProperties(prefix = "bar") @Bean public BarComponent barComponent() { ... }
Any belongings defined with the bar prefix volition be mapped onto that BarComponent edible bean in a like manner as the FooProperties instance above.
24.7.2 Relaxed binding
Spring Kicking uses some relaxed rules for bounden Surroundings properties to @ConfigurationProperties beans, so there doesn't demand to be an exact match between the Surroundings property name and the bean property name. Common examples where this is useful include dashed separated (eastward.m. context-path binds to contextPath), and capitalized (e.1000. PORT binds to port) environs backdrop.
For example, given the post-obit @ConfigurationProperties class:
@ConfigurationProperties(prefix="person") public course OwnerProperties { private String firstName; public String getFirstName() { return this.firstName; } public void setFirstName(Cord firstName) { this.firstName = firstName; } }
The following properties names can all exist used:
Table 24.ane. relaxed binding
| Property | Annotation |
|---|---|
| | Standard camel case syntax. |
| | Dashed notation, recommended for use in |
| | Underscore notation, alternative format for use in |
| | Upper instance format. Recommended when using a system environment variables. |
24.vii.3 Properties conversion
Spring will endeavour to coerce the external application properties to the right blazon when it binds to the @ConfigurationProperties beans. If you need custom type conversion y'all can provide a ConversionService bean (with bean id conversionService) or custom property editors (via a CustomEditorConfigurer bean) or custom Converters (with bean definitions annotated every bit @ConfigurationPropertiesBinding).
| Annotation |
|---|---|
| As this edible bean is requested very early during the awarding lifecycle, brand certain to limit the dependencies that your |
24.7.4 @ConfigurationProperties Validation
Spring Kicking volition attempt to validate @ConfigurationProperties classes whenever they are annotated with Spring's @Validated notation. You can use JSR-303 javax.validation constraint annotations directly on your configuration form. But ensure that a compliant JSR-303 implementation is on your classpath, then add constraint annotations to your fields:
@ConfigurationProperties(prefix="foo") @Validated public class FooProperties { @NotNull private InetAddress remoteAddress; }
In gild to validate values of nested properties, you must annotate the associated field as @Valid to trigger its validation. For instance, building upon the above FooProperties case:
@ConfigurationProperties(prefix="connectedness") @Validated public class FooProperties { @NotNull private InetAddress remoteAddress; @Valid private final Security security = new Security(); public static class Security { @NotEmpty public String username; } }
You can as well add together a custom Spring Validator by creating a bean definition called configurationPropertiesValidator. The @Bean method should be declared static. The configuration properties validator is created very early on in the application's lifecycle and declaring the @Bean method as static allows the bean to be created without having to instantiate the @Configuration class. This avoids any bug that may be caused by early instantiation. There is a property validation sample so you tin see how to set up things up.
| Tip |
|---|---|
| The |
24.7.5 @ConfigurationProperties vs. @Value
@Value is a core container characteristic and it does not provide the aforementioned features every bit type-rubber Configuration Backdrop. The table beneath summarizes the features that are supported by @ConfigurationProperties and @Value:
If yous define a ready of configuration keys for your own components, nosotros recommend you to group them in a POJO annotated with @ConfigurationProperties. Please too be aware that since @Value does not support relaxed bounden, information technology isn't a swell candidate if you need to provide the value using surround variables.
Finally, while y'all can write a SpEL expression in @Value, such expressions are not processed from Awarding holding files.
Read Environment Variable in Properties File Spring Boot
Source: https://docs.spring.io/spring-boot/docs/1.5.6.RELEASE/reference/html/boot-features-external-config.html
0 Response to "Read Environment Variable in Properties File Spring Boot"
Post a Comment