SpringBoot 配置文件

SpringBoot 配置文件详解

Posted on 2020-11-09,8 min read

SpringBoot使用一个全局的配置文件,配置文件名的

  • application.properties
  • application.yml

配置文件的作用 : SpringBoot底层都给我们配置好了,但有时候我们需要修改一些默认配置。

一、YMAL

1. YMAL与XML对比

YMAL :

server
  port: 8081

XML :

<server>
	<port>8081</port>
</server>

###2. 基本语法 k:空格v : 表示一对键值对(空格必须有)
空格的缩进来控制层级关系;空格多少无所谓,只要左对齐的一列数据,都是同一个层级的。

server:
	port: 8081
	path: /hello

3. 配置文件值注入

application.yml

server:
  port: 8081

person:
  lastName: zhangsan # 也可写成(松散语法) last-name:zhansang
  age: 18
  boss: false
  birth: 2017/12/12
  map: {k1: v1, k2 : 12}
  list:
    - lisi
    - zhaoliu
  dog:
    name: 史努比
    age: 2
cat:
  name: Tom
  age: 5

实体类 Person

package com.gf.entity;


import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 将配置文件中的配置,映射到这个组件中
 * @ConfigurationProperties: 告诉SpringBoot将本类所有属性和配置文件中相关的配置进行绑定
 *      prefix = "person" : 配置文件中那个下面的所有属性进行一一映射
 * 只有这个这个组件是容器中的组件,才能使用容器提供的@ConfigurationProperties的功能
 */
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
    private String lastName;
    private Integer age;
    private Boolean boss;
    private Date birth;

    private Map<String , Object> map;
    private List<Object> list;
    private Dog dog;

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Boolean getBoss() {
        return boss;
    }

    public void setBoss(Boolean boss) {
        this.boss = boss;
    }

    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }

    public Map<String, Object> getMap() {
        return map;
    }

    public void setMap(Map<String, Object> map) {
        this.map = map;
    }

    public List<Object> getList() {
        return list;
    }

    public void setList(List<Object> list) {
        this.list = list;
    }

    public Dog getDog() {
        return dog;
    }

    public void setDog(Dog dog) {
        this.dog = dog;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder( "{\"Person\":{" );
        sb.append( "\"lastName\":\"" )
                .append( lastName ).append( '\"' );
        sb.append( ",\"age\":" )
                .append( age );
        sb.append( ",\"boss\":" )
                .append( boss );
        sb.append( ",\"birth\":\"" )
                .append( birth ).append( '\"' );
        sb.append( ",\"map\":" )
                .append( map );
        sb.append( ",\"list\":" )
                .append( list );
        sb.append( ",\"dog\":" )
                .append( dog );
        sb.append( "}}" );
        return sb.toString();
    }
}

实体类 Dog

package com.gf.entity;


public class Dog {

    private String name;
    private Integer age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder( "{\"Dog\":{" );
        sb.append( "\"name\":\"" )
                .append( name ).append( '\"' );
        sb.append( ",\"age\":" )
                .append( age );
        sb.append( "}}" );
        return sb.toString();
    }
}

实体类 Cat

package com.gf.entity;

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

@Component
public class Cat {
    @Value( "${cat.name}" )
    private String name;
    @Value( "${cat.age}" )
    private Integer age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder( "{\"Cat\":{" );
        sb.append( "\"name\":\"" )
                .append( name ).append( '\"' );
        sb.append( ",\"age\":" )
                .append( age );
        sb.append( "}}" );
        return sb.toString();
    }
}

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.gf</groupId>
	<artifactId>springboot-config</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>springboot-config</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.9.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<!-- 导入配置文件处理器,配置文件进行绑定就会有提示 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-configuration-processor</artifactId>
			<optional>true</optional>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>


</project>

SpringBoot 测试类

package com.gf;

import com.gf.entity.Cat;
import com.gf.entity.Person;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * SpringBoot单元测试
 * 可以在测试期间很方便的类似编码一样进行自动注入等容器的功能
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootConfigApplicationTests {

	@Autowired
	Person person;

	@Autowired
	Cat cat;

	@Test
	public void contextLoads() {
		System.out.println(person);
		System.out.println(cat);
	}

}

运行 SpringbootConfigApplicationTests 的到结果

{
	"Person": {
		"lastName": "zhangsan",
		"age": 18,
		"boss": false,
		"birth": "Tue Dec 12 00:00:00 CST 2017",
		"map": {
			k1 = v1,
			k2 = 12
		},
		"list": [lisi, zhaoliu],
		"dog": {
			"Dog": {
				"name": "史努比",
				"age": 2
			}
		}
	}
} 
{
	"Cat": {
		"name": "Tom",
		"age": 5
	}
}

@Value获取值和@ConfigurationProperties获取值比较

@ConfigurationProperties @Value
功能 批量注入文件中的属性 一个一个指定
松散绑定(松散语法) 支持 不支持
SpEL 不支持 支持
JSR303数据校验 支持 不支持
复杂类型封装 支持 不支持
如果说,我们只是在某个业务逻辑中需要获取一下配置文件中的某项值,使用**@Value**;
如果说,我们专门编写了一个javaBean来和配置文件进行映射,我们就直接使用**@ConfigurationProperties**;

下一篇: 构建一个SpringBoot工程→