一、Springboot中參數的設置
1,使用框架默認配置文件
springboot配置文件,默認配置文件application.propertie或者application.yml,可同時存在。設置系統參數和自定義參數直接在此類配置文件中配置即可。
一般項key=value方式,properties的數組使用
1 user.girlFriends[0]=1
2 user.girlFriends[0]=2
3 user.girlFriends[0]=3
4 user.girlFriends[0]=4
yaml的數組使用
1 user 2 girlFriends 3 - 1
4 - 2
5 - 3
6 - 4
2,使用自定義配置文件
可以自己創建一個user.properties文件,只需要在讀取時,使用@PropertySource注解即可
1 @Data 2 @Component 3 @PropertySource(value = "classpath:user.properties") 4 @ConfigurationProperties(prefix = "user") 5 public class UserProperties { 6 private String username; 7 }
二、Springboot中參數的獲取
1,使用@Value注解
1 @Value("${user.username}") 2 private String username;
2,使用Environment對象
1 @Autowired 2 private Environment environment;
然后在需要的地方
1 environment.getProperty("user.username")
3,使用@ConfigurationProperties
激活@ConfigurationProperties(配置類被spring掃到)的方式有很多,@Component是最簡單的一種
1 @Data 2 @Component 3 @ConfigurationProperties(prefix = "user") 4 public class UserProperties { 5 private String username; 6 }
還可以用配置類加下面
1 @Configuration 2 class PropertiesConfiguration { 3 @Bean 4 public UserProperties userProperties() { 5 return new UserProperties(); 6 } 7 }
也可以用配置類加下面
1 @Configuration 2 @EnableConfigurationProperties(UserProperties.class) 3 class PropertiesConfiguration { 4 }
三、Profile
假設我們建立了兩個配置文件:application-dev.properties和allpication-pro.properties,里邊的key完全一樣,只是value不同,一個用於開發一個用於線上。這兩個配置文件我們就稱我們的系統有兩個profile,使用那個有幾種配置方式。
1,在appliapplication.properties中指定(yml文件類似)
1 spring.profiles.active=dev
2,在程序啟動參數中設置
1 --spring.profiles.active=dev
3,在程序啟動時使用VM參數
1 -Dspring.profiles.active=dev
