sunmingtao / sample-code

3 stars 4 forks source link

How does Spring boot look for properties in Environment variables #53

Closed sunmingtao closed 5 years ago

sunmingtao commented 5 years ago

Annotate a string

@Value("${smtp.port}")
private Integer smtpPort;

If you define an environment variable, SMTP_PORT=25, spring boot is able to find and inject 25 to smtpPort

sunmingtao commented 5 years ago

The spring boot property resolution order is

Devtools global settings properties on your home directory (~/.spring-boot-devtools.properties when devtools is active).
@TestPropertySource annotations on your tests.
@SpringBootTest#properties annotation attribute on your tests.
Command line arguments.
Properties from SPRING_APPLICATION_JSON (inline JSON embedded in an environment variable or system property)
ServletConfig init parameters.
ServletContext init parameters.
JNDI attributes from java:comp/env.
Java System properties (System.getProperties()).
OS environment variables.
A RandomValuePropertySource that only has properties in random.*.
Profile-specific application properties outside of your packaged jar (application-{profile}.properties and YAML variants)
Profile-specific application properties packaged inside your jar (application-{profile}.properties and YAML variants)
Application properties outside of your packaged jar (application.properties and YAML variants).
Application properties packaged inside your jar (application.properties and YAML variants).
@PropertySource annotations on your @Configuration classes.
Default properties (specified using SpringApplication.setDefaultProperties).

https://www.java2novice.com/spring-boot/property-resolution-order/

When spring boot searches in the environment variables, it doesn't translate environment variables to spring properties, rather it checks if environment variable matches the spring property.

e.g. smtp.port matches SMTP_PORT smtp.port_new matches SMTP_PORT_NEW smtp.port.new also matches SMTP_PORT_NEW

https://stackoverflow.com/questions/34178556/how-to-set-a-spring-boot-property-with-an-underscore-in-its-name-via-environment