1. 程式人生 > >springboot學習三 SpringBoot的環境配置

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>