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
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
).
例如:在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>