SpringBoot配置文件

SpringBoot目标是零配置。

SpringBoot提供了或者说推荐了两种配置方式:

1.properties文件
2.yml配置文件

 

1.yml中如何去写配置文件:

普通的写法:(字符串 数字  boolean类型 等单个值)

stuname: 张三
stuage: 10
ifchengnian: false
集合数组的写法:
stuaddress:
- 学校
- 济南
- 家庭
如果是对象或者map集合:
dept:
deptno: 10
dname: hello
loc: world

 

2.配置的数据如何读取到程序中

单个值读取:

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
@Data
public class Student {
   @Value("${stuname}")
   private String stuname;
   @Value("${stuage}")
   private int stuage;
   @Value("${ifchengnian}")
   private boolean ifchengnian;
}

 

配置整个对象和属性的关系:

package com.zhuoyue.democonfig;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@Data
@ConfigurationProperties(prefix = "dept")
public class Dept {

//   @Value("${dept.deptno}")
   private  int deptno;
   private String dname;
   private String loc;

}

 

SPEL:

SP: Spring

El: EL表达式

3.三个和配置相关的注解

@PropertySource可以读取指定的配置文件
@ImportResource可以读取外部的spring配置文件
@Configuration
@Bean可以给容器中添加一个类对象

resourcces/dog.properties

dog.dname=tangyuan
dog.age=3

@PropertySource可以读取指定的配置文件

Dog.java

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "dog")
@Data
@PropertySource(value={"classpath:dog.properties"})
public class Dog {
   private String dname;
   private int age;
}

 

 

 

 

@ImportResource可以读取外部的spring配置文件

需要读取谁就在主启动类的上方引入这个配置即可,例如:

@SpringBootApplication
@ImportResource(locations = {"classpath:spring.xml"})
public class DemoconfigApplication {

   public static void main(String[] args) {
       SpringApplication.run(DemoconfigApplication.class, args);
  }

}

 

 

@Bean的作用

@Bean
   public Cat cat(){
       Cat cat = new Cat();
       cat.setCatName("花花");
       cat.setCatAge(5);
       return cat;
  }
import com.zhuoyue.democonfig.po.Cat;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SuiBian {

   @Bean
   public Cat cat(){
       Cat cat = new Cat();
       cat.setCatName("花花");
       cat.setCatAge(5);
       return cat;
  }

}

 

4.配置文件的占位符

user.username=zhangsan
user.jieshao=wo de ming zi jiao ${user.username}${random.int(10)}

 

5.多环境开发

springboot支持多种环境下的配置文件,用哪一个需要在application.properties配置文件中进行指定:

application.yml;application-dev.yml;application-test.yml;application-prod.yml

spring.profiles.active=test

 

 

6.配置文件的位置

两个位置,一个直接写在resources根目录下
或者,resources/config下都行