深刻理解SpringBoot配置

1、application.properties的位置

1.當前目錄的 「/config」的子目錄下
2.當前目錄下
3.classpath根目錄的「/config」包下
4.classpath的根目錄下html

spring會從classpath下的/config目錄或者classpath的根目錄查找application.properties或application.yml。java

/config優先於classpath根目錄spring

說明:mongodb

  1. 1,2兩項適合生產環境,能夠直接跟jar包放在同級目錄下
  2. 若是同時在四個地方都有配置文件,配置文件的優先級是從1到4。
  3. 使用配置文件以後,spring boo啓動時,會自動把配置信息讀取到spring容器中,並覆蓋spring boot的默認配置

SpringBoot的配置方式有不少,它們的優先級以下所示(優先級遞減順序):express

  1. 命令行參數
  2. 來自java:comp/env的JNDI屬性
  3. Java系統屬性(System.getProperties())
  4. 操做系統環境變量
  5. RandomValuePropertySource配置的random.*屬性值
  6. jar包外部的application-{profile}.propertiesapplication.yml(帶spring.profile)配置文件
  7. jar包內部的application-{profile}.propertiesapplication.yml(帶spring.profile)配置文件
  8. jar包外部的application.propertiesapplication.yml(不帶spring.profile)配置文件
  9. jar包內部的application.propertiesapplication.yml(不帶spring.profile)配置文件
  10. @Configuration註解類上的@PropertySource
  11. 經過SpringApplication.setDefaultProperties指定的默認屬性

由於jar包外部的優先級高,因此能夠運行時指定application.properties的位置。
以上配置方式雖然挺多,實際用到的只有一兩種。json

2、 經過命令行來配置少許項

SpringBoot能夠不依賴Tomcat容器,做爲單應用啓動。這時,能夠經過命令行來控制運行參數。
經過命令行來重寫和配置環境變量,優先級最高,例如能夠經過下面的命令來重寫spring boot 內嵌tomcat的服務端口,注意「=」倆邊不要有空格
java -jar demo.jar --server.port=9000
若是想要設置多個變量怎麼辦,能夠用json的格式字符串來設置
java -jar demo.jar --spring.application.json='{"foo":"bar"}'tomcat

3、 使用@Value註解

@RestController
@RequestMapping("/task")
public class TaskController {

@Value("${connection.remoteAddress}") private String address;

@RequestMapping(value = {"/",""})
public String hellTask(@Value("${connection.username}")String name){

    return "hello task !!";
}
}

@Value註解有好幾種姿式:
1. #{expression?:default value}springboot

@Value("#{systemProjecties['mongodb.port']?:27017}")
private String mongodbPort;
@Value("#{config['mongodb.url']?:'127.0.0.1'}")
private String mongodbUrl;
@Value("#{aBean.age ?:21}")
private int age;

2. ${property:default value}session

//@propertySource("classpath:/config.properties")
//configuration
@Value("${mongodb.url:127.0.0.1}")
private String mongodbUrl;
@Value("#{'${mongodb.url:172.0.0.1}'}")
private String mongoUrl;
@Value("#config['mongodb.url']?:'127.0.0.1'")
private String mogodbUrl;

配置文件config.property以下:app

mogodb.url = 1.2.3.4
mogodb.db = hello

3. 注意
Must register a static PropertySourcesPlaceholderConfiger bean in either XML or annotation ,so that Spring @Value konw how to interpret ${}

//@PropertySource("classpath:/config.properties}")
//@Configuration
  @Bean
  public static PropertySourcesPlaceholderConfigurer propertyConfigIn() {
         return new PropertySourcesPlaceholderConfigurer();
  }

4、 屬性的引用

myapp.name=spring
myapp.desc=${myapp.name} nice
SpringBoot提供如下特殊引用:
my.secret=${random.value}
my.number=${random.int}
my.bignumber=${random.long}
my.number.less.than.ten=${random.int(10)}
my.number.in.range=${random.int[1024,65536]}

5、 自定義配置信息

@Component
public class SystemConfig {

    private static Properties props ;

    public SystemConfig(){

        try {
            Resource resource = new ClassPathResource("/application.properties");//
            props = PropertiesLoaderUtils.loadProperties(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 獲取屬性
     * @param key
     * @return
     */
    public static String getProperty(String key){

        return props == null ? null :  props.getProperty(key);

    }

    /**
     * 獲取屬性
     * @param key 屬性key
     * @param defaultValue 屬性value
     * @return
     */
    public static String getProperty(String key,String defaultValue){

         return props == null ? null : props.getProperty(key, defaultValue);

    }

    /**
     * 獲取properyies屬性
     * @return
     */
    public static Properties getProperties(){
        return props;
    }

}

//用的話,就直接這樣子
String value = SystemConfig.getProperty("key");

6、SpringBoot自帶的配置屬性

經常使用屬性如日誌,端口配置

# LOGGING
logging.path=/var/logs
logging.file=myapp.log
logging.config= # location of config file (default classpath:logback.xml for logback)
logging.level.*= # levels for loggers, e.g. "logging.level.org.springframework=DEBUG" (TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF)

# EMBEDDED SERVER CONFIGURATION (ServerProperties)
server.port=8080
server.address= # bind to a specific NIC
server.session-timeout= # session timeout in seconds
server.context-parameters.*= # Servlet context init parameters, e.g. server.context-parameters.a=alpha
server.context-path= # the context path, defaults to '/'
server.servlet-path= # the servlet path, defaults to '/'

更多屬性參見官網文檔

@ContextConfiguration
@ContextConfiguration(locations={"classpath*:mongodb.xml"})

7、屬性名匹配規則

例若有以下配置對象:

@Component
@ConfigurationProperties(prefix="person")
public class ConnectionSettings {

    private String firstName;

}

firstName可使用的屬性名以下:

person.firstName,標準的駝峯式命名
person.first-name,虛線(-)分割方式,推薦在.properties和.yml配置文件中使用
PERSON_FIRST_NAME,大寫下劃線形式,建議在系統環境變量中使用

參考資料

偶爾記一下

相關文章
相關標籤/搜索