Springboot中参数设置与获取之@Value、Environment、properties、profile

一、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
原文地址:https://www.cnblogs.com/guanghe/p/13397249.html