SpringBoot configuration file
One, configuration file
a) Basic introduction
① SpringBoot uses a global configuration file, and the configuration file name is fixed:application.properies;application.yml
② The function of the configuration file is to modify the default value of springBoot automatic configuration (SpringBoot automatically configures us at the bottom)
Two, YAML
a) Basic introduction
YAML is a recursive acronym for "YAML Ain't a Markup Language" (YAML is not a markup language). When developing this language, YAML actually meant: "Yet Another Markup Language" (still a markup language).
① Advantages: previous profile, mostly using xxxx.xml file; YAML:Data-centric, Which is more suitable for configuration files than json, xml, etc. , as shown in the following examples:
#yaml配置文件(显然YAML更加简洁不冗杂,更加适合做配置文件!)
server:
port: 8081
<!--XML配置文件-->
<server>
<port>8081</port>
</server>
b) YAML syntax
1) Basic use
① key: (space) value: a pair of key-value pairs (spaces must be present)
② Use space indentation to control the hierarchical relationship; as long as a column of data is left-aligned, they are all at the same level
③ Attributes and values are case sensitive
④'#' means comment
⑤ Tabs are not allowed for indentation,Only allow spaces
server:
port: 8088
path: /hello
2) Data Type Support
① literal: Common values (numbers, strings, Boolean)
Write directly literally: key: value
Strings do not need to be enclosed in single or double quotation marks by default (you can use double quotation marks or single quotation marks to wrap special characters )
② objects, Map (attributes and values) (key-value pairs)
Object/Map is also a way of key: value
friends:
lastName: zhangsan
age: 20
#行内写法
friends: {
lastName: zhangsan,age: 18}
③ array (List, set)
To - beginning of the line represents an element in an array
pets: - cat - dog - pig #行内写法 pets: [cat,dog,pig]
Three, configuration file value injection
a)javaBean
/**
* 将配置文件中配置的每一个属性的值,映射到这个组件中
* @ConfigurationProperties:告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定;
* prefix = "person":配置文件中哪个下面的所有属性进行一一映射
*
* 只有这个组件是容器中的组件,才能容器提供的@ConfigurationProperties功能;
*
*/
@Component
@ConfigurationProperties(prefix = "person")
@Validated//数据校验
public class Person {
//@Email(加上注解后限制lastName必须是邮箱格式)
private String lastName;
private Integer age;
private Boolean boss;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
b) Configuration file injection properties
person:
lastName: hello
age: 18
boss: false
birth: 2017/12/12
maps: {
zhangsan: 23,wangwu: 25}
lists:
- lisi
- zhaoliu
dog:
name: 小狗
age: 12
<!--在项目Pom中导入配置文件处理器,配置文件进行绑定就会有提示-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
c) Annotate @Value to inject properties
@Component
public class Person {
@Value("${person.name:HelloWorld!}")
private String lastName;
@Value("#{11*2}")
private Integer age;
@Value("true")
private Boolean boss;
//复杂类型无法封装
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
d) Comparison of @Value acquisition value and @ConfigurationProperties acquisition value
@ConfigurationProperties | @Value | |
---|---|---|
Features | Bulk injection of properties in configuration files | Specify one by one |
Loosely bound (loose syntax) | stand by | not support |
Game | not support | stand by |
JSR303 data verification | stand by | not support |
Complex type package | stand by | not support |
Configuration files yml and properties can get values. If we just need to get a value in the configuration file in a certain business logic, use @Value; if we write a javaBean to map with the configuration file, We use @ConfigurationProperties directly
e)@PropertySource&@ImportResource&@Bean
① @PropertySource : Load the specified configuration file
#person.properties文件
person.last-name=李四
person.age=12
person.birth=2017/12/15
person.boss=false
person.maps.k1=v1
person.maps.k2=14
person.lists=a,b,c
person.dog.name=dog
person.dog.age=15
@PropertySource(value = {
"classpath:person.properties"})//类路径下加载属性
@Component
@ConfigurationProperties(prefix = "person")
//@Validated
public class Person {
private String lastName;
private Integer age;
private Boolean boss;
② @ImportResource : Import the Spring configuration file, let the configuration file
There is no Spring configuration file in Spring Boot. The configuration file we wrote by ourselves cannot be automatically recognized. To make the Spring configuration file effective (loaded in), @ ImportResource is marked on a configuration class
@ImportResource(locations = { "classpath:beans.xml"})//导入Spring的配置文件让其生效 @SpringBootApplication public class SpringBoot02ConfigApplication { public static void main(String[] args) { SpringApplication.run(SpringBoot02ConfigApplication.class, args); } }
<?xml version="1.0" encoding="UTF-8"?><!--beans.xml配置文件--> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="helloService" class="com.atguigu.springboot.service.HelloService"></bean> </beans>
③ @bean
SpringBoot recommends the way to add components to the container ;It is recommended to use the full annotation method
1. Configuration class **@Configuration**------>Spring configuration file
2. Use **@Bean** to add components to the container
/** * @Configuration:指明当前类是一个配置类;用来替代之前的Spring配置文件 * * 以前在配置文件中用<bean><bean/>标签添加组件 * */ @Configuration public class MyAppConfig { //将方法的返回值添加到容器中;容器中这个组件默认的id就是方法名 @Bean public HelloService helloService02(){ System.out.println("配置类@Bean给容器中添加组件了..."); return new HelloService(); } }
Four, configuration file placeholder
a) Random number
${
random.value}、${
random.int}、${
random.long}
${
random.int(10)}、${
random.int[1024,65536]}
b) The placeholder gets the previously configured value, if not, it can beUse: Specify the default value
person.last-name=张三${random.uuid}
person.age=${random.int}
person.birth=2017/12/15
person.boss=false
person.maps.k1=v1
person.maps.k2=14
person.lists=a,b,c
person.dog.name=${person.hello:hello}_dog
person.dog.age=15
Five, Profile
a) Multiple Profile files
When the main configuration file is written, the file name can be application-{profile}.properties/yml, and the configuration of application.properties is used by default
b) yml supports multi-document block mode
server:
port: 8081
spring:
profiles:
active: prod
---
server:
port: 8083
spring:
profiles: dev
---
server:
port: 8084
spring:
profiles: prod #指定属于哪个环境
c) Activate the specified profile
1. Specify spring.profiles.active=dev in the configuration file
2. Command line:
java -jar spring-boot-02-config-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev (You can directly configure the incoming command line parameters when testing)
3. Virtual machine parameters;
-Dspring.profiles.active=dev
Six, configuration file loading location
Springboot startup will scan the application.properties or application.yml files in the following locations as the default configuration file for Spring boot; the priority is from high to the bottom, and the configuration with high priority will override the configuration with low priority; SpringBoot will start from these four locations All load the main configuration file, complementary configuration.
–file:./config/
–file:./
–classpath:/config/
–classpath:/