springboot学习(三) springboot文件配置

1、简介

  springboot没有了原来自己整合Spring应用时繁多的XML配置内容,替代它的是在pom.xml中引入模块化的Starter POMs,其中各个模块都有自己的默认配置,所以如果不是特殊应用场景,就只需要在application.properties中完成一些属性配置就能开启各模块的应用。

 

 2、自定义属性和加载

  我们使用的时候在application.properties中定义一些自己使用的属性:

1 com.cnblogs.name=origalom
2 com.cnblogs.title=学习Spring Boot

  然后在代码中利用@Value("${属性名}")注解来获取对应的配置的值:

 1 @Component
 2 public class Properties {
 3 
 4     @Value("${com.cnblogs.name}")
 5     private String name;
 6 
 7     @Value("${com.cnblogs.title}")
 8     private String title;
 9 
10     // ......
11 
12 }

 

  最后,编写测试代码进行测试,查看是否可以正常获取到配置中的数据:

 1 @RunWith(SpringRunner.class)
 2 @SpringBootTest(classes = Application.class)
 3 public class TestProperties {
 4 
 5     @Autowired
 6     private Properties properties;
 7 
 8     @Test
 9     public void test() {
10         System.out.println(properties.getName());
11         System.out.println(properties.getTitle());
12     }
13 }

 

 

3、参数间的引用

  在配置文件中参数之间是可以直接引用的,方法为${属性名}:

1 com.cnblogs.name=origalom
2 com.cnblogs.title=学习Spring Boot
3 com.cnblogs.desc=${com.cnblogs.name.name}正在${com.cnblogs.title}

 

 

4、使用随机数

  有时,我们需要的参数不是一个固定的数,而是随机的一个数。这个时候我们就可以通过${random}来产生随机数:

 1 # 随机字符串
 2 com.cnblogs.value=${random.value}
 3 # 随机整数
 4 com.cnblogs.int=${random.int}
 5 # 随机long
 6 com.cnblogs.long=${random.long}
 7 # 100以内的随机整数
 8 com.cnblogs.int1=${random.int(100)}
 9 # 100-200之间的随机整数
10 com.cnblogs.int2=${random.int[100,200]}
11 # 随机uuid
12 com.cnblogs.uuid=${random.uuid}

 

 

5、通过命令行设置属性值

  默认情况下,SpringApplication将任何可选的命令行参数(以'--'开头,比如,--server.port=9000)转化为property,并将其添加到Spring Environment中。如上所述,命令行属性总是优先于其他属性源。

  如果不想使用命令行的形式,可以通过设置取消这个功能:

1 SpringApplication application = new SpringApplication(Application.class);
2 // 取消通过命令行设置属性值
3 application.setAddCommandLineProperties(false);
4 application.run(Application.class, args);

 

 

6、多环境配置

  一般情况下,应用程序会被安装到不同的环境中,比如开发,测试,生产等,而在这些环境中数据库,服务器端口号等配置可能不同,所以很容易发生错误。

  在spring boot中,多环境配置文件名需要满足application-{profile}.properties的格式,其中{profile}对应你的环境标识:

  •   application-dev.properties: 开发环境
  •        application-test.properties: 测试环境
  •        application-prod.properties: 生产环境

  然后,可以在application.properties中设置spring.profiles.active来确定使用哪个环境,其值对应{profile}值。

 

posted on 2018-01-20 15:36  程序员AI  阅读(165)  评论(0编辑  收藏  举报

导航