springboot學習三 SpringBoot的環境配置
阿新 • • 發佈:2018-11-04
SpringBoot集成了很多常用的第三方jar包,比如mysql,redis等,並且內部也做了很多的預設配置,具體可以看spring-boot-autoconfigure-1.5.6.RELEASE.jar內部的各種配置類,當然SpringBoot也提供了我們自己能夠自己配置環境。
SpringBoot提供了很多的自定義配置環境的方式,當然,這些配置有個順序:
- 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 inrandom.*
. - Profile-specific application properties outside of your packaged jar (
application-{profile}.properties
- 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
).
例如:在application.properties配置
name=helloworld
java程式碼中讀取
@RestController
@EnableAutoConfiguration
public class App {
@Value("${name}")
private String name;
@RequestMapping("/")
String home() {
return name;
}
public static void main(String[] args){
SpringApplication.run(App.class,args);
}
}
頁面訪問測試:
1.SpringBoot提供了在Application.properties中設定隨機值
my.secret=${random.value}
my.number=${random.int}
my.bignumber=${random.long}
my.uuid=${random.uuid}
my.number.less.than.ten=${random.int(10)}
my.number.in.range=${random.int[1024,65536]}
2.設定命令列properties
預設的SpringApplication將會把命令列轉化成一個property新增到Spring環境中,命令列總是優先於其它的屬性資源.
如果不想命令列被新增到Environment中,可以作如下設定,就會失效
<span style="color:#6d180b">SpringApplication.setAddCommandLineProperties(false)</span>