springboot学习三 SpringBoot的环境配置

SpringBoot集成了很多常用的第三方jar包,比如mysql,redis等,并且内部也做了很多的默认配置,具体可以看spring-boot-autoconfigure-1.5.6.RELEASE.jar内部的各种配置类,当然SpringBoot也提供了我们自己能够自己配置环境。

SpringBoot提供了很多的自定义配置环境的方式,当然,这些配置有个顺序:

  1. Devtools global settings properties on your home directory (~/.spring-boot-devtools.properties when devtools is active).
  2. @TestPropertySource annotations on your tests.
  3. @SpringBootTest#properties annotation attribute on your tests.
  4. Command line arguments.
  5. Properties from SPRING_APPLICATION_JSON (inline JSON embedded in an environment variable or system property)
  6. ServletConfig init parameters.
  7. ServletContext init parameters.
  8. JNDI attributes from java:comp/env.
  9. Java System properties (System.getProperties()).
  10. OS environment variables.
  11. RandomValuePropertySource that only has properties in random.*.
  12. Profile-specific application properties outside of your packaged jar (application-{profile}.properties and YAML variants)
  13. Profile-specific application properties packaged inside your jar (application-{profile}.properties and YAML variants)
  14. Application properties outside of your packaged jar (application.properties and YAML variants).
  15. Application properties packaged inside your jar (application.properties and YAML variants).
  16. @PropertySource annotations on your @Configuration classes.
  17. 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>

猜你喜欢

转载自blog.csdn.net/strong_yu/article/details/77622705