一、application.properties的位置
1.當前目錄的 “/config”的子目錄下
2.當前目錄下
3.classpath根目錄的“/config”包下
4.classpath的根目錄下
spring會從classpath下的/config目錄或者classpath的根目錄查找application.properties或application.yml。
/config優先于classpath根目錄
Spring配置?說明:
- 1,2兩項適合生產環境,可以直接跟jar包放在同級目錄下
- 如果同時在四個地方都有配置文件,配置文件的優先級是從1到4。
- 使用配置文件之后,spring boo啟動時,會自動把配置信息讀取到spring容器中,并覆蓋spring boot的默認配置
SpringBoot的配置方式有很多,它們的優先級如下所示(優先級遞減順序):
- 命令行參數
- 來自java:comp/env的JNDI屬性
- Java系統屬性(System.getProperties())
- 操作系統環境變量
- RandomValuePropertySource配置的random.*屬性值
- jar包外部的
application-{profile}.properties
或application.yml
(帶spring.profile)配置文件 - jar包內部的
application-{profile}.properties
或application.yml
(帶spring.profile)配置文件 - jar包外部的
application.properties
或application.yml
(不帶spring.profile)配置文件 - jar包內部的
application.properties
或application.yml
(不帶spring.profile)配置文件 @Configuration
注解類上的@PropertySource
- 通過
SpringApplication.setDefaultProperties
指定的默認屬性
因為jar包外部的優先級高,所以可以運行時指定application.properties的位置。
以上配置方式雖然挺多,實際用到的只有一兩種。
二、 通過命令行來配置少量項
SpringBoot可以不依賴Tomcat容器,作為單應用啟動。這時,可以通過命令行來控制運行參數。
通過命令行來重寫和配置環境變量,優先級最高,例如可以通過下面的命令來重寫spring boot 內嵌tomcat的服務端口,注意“=”倆邊不要有空格
java -jar demo.jar --server.port=9000
如果想要設置多個變量怎么辦,可以用json的格式字符串來設置
java -jar demo.jar --spring.application.json='{"foo":"bar"}'
三、 使用@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 !!";
}
}
spring配置中心,@Value注解有好幾種姿勢:
1. #{expression?:default value}
@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}
//@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如下:
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@Beanpublic static PropertySourcesPlaceholderConfigurer propertyConfigIn() {return new PropertySourcesPlaceholderConfigurer();}
四、 屬性的引用
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]}
五、 自定義配置信息
@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");
六、SpringBoot自帶的配置屬性
spring基礎配置,常用屬性如日志,端口配置
# 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"})
七、屬性名匹配規則
例如有如下配置對象:
@Component
@ConfigurationProperties(prefix="person")
public class ConnectionSettings {private String firstName;}
spring配置類,firstName可以使用的屬性名如下:
person.firstName
,標準的駝峰式命名person.first-name
,虛線(-)分割方式,推薦在.properties和.yml配置文件中使用PERSON_FIRST_NAME
,大寫下劃線形式,建議在系統環境變量中使用
參考資料
偶爾記一下