Spring Boot入门<二>spring boot 的配置与配置文件

一.spring-boot的spring-beans.xml与配置类

(一)@ImportResource(locations="{classpath:spring.xml}")

SpringBoot不会自动识别spring-beans.xml文件,所以需要用@ImportResource来进行引入,但是此种方法不推荐

(二)配置类:SpringBoot会自动配置相关类,但有些场景不能满足时需要自己进行类的配置,这时就需要用配置类实现

 1 import org.springframework.context.annotation.Bean;
 2 import org.springframework.context.annotation.Configuration;
 3 
 4 @Configuration
 5 public class AppConfigruation {
 6     @Bean
 7     public ConfigruationService configruationService(){
 8         return new ConfigruationService();
 9     }
10 }
1 @Test
2     public void appGetConfig(){
3         ApplicationContext context = new AnnotationConfigApplicationContext(AppConfigruation.class);
4         ConfigruationService serice = (ConfigruationService) context.getBean("configruationService");
5         System.out.println(serice);
6     }

 

二.多环境设置与切换

方式一.properties文件

1.添加application-环境名称.properties的配置文件

2.在application.properties中配置spring.profiles.active=环境名称

方式二.yaml文件

spring:
    profiles:
        active:dev
---
spring:
    profiles: dev
---
spring:
    profiles: test
---

方式三:利用编译器或者vm虚拟机添加参数运行不同的环境

编译器:在IDE中Run Configruation-arguments中, --spring.profiles.active=环境名

    在命令行中:Java -jar Xxx.jar -spring.profiles.active=环境名

VM参数:在IDE中Run Configruation-vm中 -Dspring.profiles.active=环境名

三.配置文件

1.内部配置文件

application.propertise/application.yml可以存在于以下四个目录

file:项目根目录/conf

file:项目根目录

classpath:项目根目录/conf

classpath:项目根目录

2.外部配置文件

在运行时添加参数:spring.config.location=文件路径

3.IDE启动配置与编译器启动配置

当需要修改的参数不多时可以利用类似多环境切换中的方式三进行参数的配置及启动

四.加载顺序

1.以上配置优先级为3>2>1

2.内部配置文件的优先级为:file:项目根目录/conf > file:项目根目录 > classpath:项目根目录/conf > classpath:项目根目录

3.当有冲突时,依照优先级高的文件,没有冲突时互相补充

4.更详细的优先级请参照https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-external-config

五.yaml中使用随机数

名称

描述

${random.value}

取得随机字符串

${random.int} 取得随机int型数据
${random.long} 取得随机long型数据
${random.int(10)} 取得10以内的随机数
${random.int[10,20]} 取得10~20的随机数

posted @ 2020-09-17 10:45  远亭  阅读(531)  评论(0)    收藏  举报