SpringBoot的配置【配置文件、加载顺序、配置原理】(超详细)

《一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码》点击传送门,即可获取!

private String lastName;

private Integer age;

private Boolean boss;

private Date birthday;

private Map<String,Object> maps;

private List lists;

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 getBirthday() {

return birthday;

}

public void setBirthday(Date birthday) {

this.birthday = birthday;

}

public Map<String, Object> getMaps() {

return maps;

}

public void setMaps(Map<String, Object> maps) {

this.maps = maps;

}

public List getLists() {

return lists;

}

public void setLists(List lists) {

this.lists = lists;

}

public Dog getDog() {

return dog;

}

public void setDog(Dog dog) {

this.dog = dog;

}

@Override

public String toString() {

return “Person{” +

“lastName='” + lastName + ‘’’ +

“, age=” + age +

“, boss=” + boss +

“, birthday=” + birthday +

“, maps=” + maps +

“, lists=” + lists +

“, dog=” + dog +

‘}’;

}

}

Dog:

package com.keafmd.springboot.bean;

/**

  • Keafmd

  • @ClassName: Dog

  • @Description:

  • @author: 牛哄哄的柯南

  • @date: 2021-02-23 12:50

*/

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() {

return “Dog{” +

“name='” + name + ‘’’ +

“, age=” + age +

‘}’;

}

}

application.yml:

person:

lastName: Keafmd

age: 18

boss: false

birthday: 2020/02/02

maps: {k1: v1,k2: v2}

lists:

  • lisi

  • zhaoliu

  • Keafmd

  • xiaolan

dog:

name: 二狗

age: 2

测试代码:

package com.keafmd.springboot;

import com.keafmd.springboot.bean.Person;

import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.test.context.SpringBootTest;

import org.springframework.context.ApplicationContext;

/**

  • SpringBoot单元测试

  • 可以再测试期间很方便的类似编码一样进行自动注入等容器

*/

@SpringBootTest

class SpringBoot02ConfigApplicationTests {

@Autowired

Person person;

@Test

public void contextLoads() {

System.out.println(person);

}

}

运行结果:

Person{lastName=‘Keafmd’, age=18, boss=false, birthday=Sun Feb 02 00:00:00 CST 2020, maps={k1=v1, k2=v2}, lists=[lisi, zhaoliu, Keafmd, xiaolan], dog=Dog{name=‘二狗’, age=2}}

导入配置文件处理器,使编写配置有提示


注意:我们可以在pom.xml中导入配置文件处理器,以后编写配置就有提示了。

org.springframework.boot

spring-boot-configuration-processor

true

properties配置文件在idea中默认utf-8可能会乱码


application.yml的person注释掉,在application.properties文件中进行编写。

application.properties:

配置person的值

person.last-name=张三

person.age=18

person.boss=false

person.birthday=2022/02/02

person.maps.k1=v1

person.maps.k2=v2

person.lists=a,b,c

person.dog.name=二狗

person.dog.age=3

我们再次运行测试代码会发现,会出现中文乱码的情况。

解决办法:

在这里插入图片描述

设置好再次运行测试代码

运行结果:

Person{lastName=‘张三’, age=18, boss=false, birthday=Sun Feb 02 00:00:00 CST 2020, maps={k1=v1, k2=v2}, lists=[a, b, c], dog=Dog{name=‘二狗’, age=3}}

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


| - | @ConfigurationProperties | @Value |

| — | — | — |

| 功能 | 批量注入配置文件中的属性 | 一个个指定 |

| 松散绑定(松散语法) | 支持 | 不支持 |

| SpEL | 不支持 | 支持 |

| JSR303数据校验 | 支持 | 不支持 |

| 复杂类型封装 | 支持 | 不支持 |

**配置文件yml还是properties他们都能获取到值

如果说,我们只是在某个业务逻辑中需要获取一下配置文件中的某项值,使用@Value

如果说,我们专门编写了一个javaBean来和配置文件进行映射,我们就直接使用@ConfigurationProperties**

application.properties:

配置person的值

person.last-name=张三

person.age=18

person.boss=false

person.birthday=2022/02/02

person.maps.k1=v1

person.maps.k2=v2

person.lists=a,b,c

person.dog.name=二狗

person.dog.age=3

Person:(部分代码,get和set以及toString不展示了)

package com.keafmd.springboot.bean;

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

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

import org.springframework.context.annotation.PropertySource;

import org.springframework.stereotype.Component;

import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.Email;

import java.util.Date;

import java.util.List;

import java.util.Map;

/**

  • Keafmd

  • @ClassName: Person

  • @Description:

  • @author: 牛哄哄的柯南

  • @date: 2021-02-23 12:47

*/

/**

  • 将配置文件中配置的每一个属性的值,映射到这个组件中

  • @ConfigurationProperties :告诉SpringBoot将本类中的所有属性和配置文件相关的配置进行绑定

  • prefix = “person” :配置文件中哪个属性进行一一映射

  • 只有这个组件时容器中的组件吗,才能使用容器提供的功能

*/

@Component

//@ConfigurationProperties(prefix = “person”)

public class Person {

/**

  • <property name = "lastName" value = "字面量/${key}从环境变量、配置文件中获取值/#{SpEL}"></property>
    

*/

@Value(“${person.last-name}”)

private String lastName;

@Value(“#{11*2}”)

private Integer age;

@Value(“true”)

private Boolean boss;

private Date birthday;

private Map<String,Object> maps;

private List lists;

private Dog dog;

}

运行测试代码的运行结果:

Person{lastName=‘张三’, age=22, boss=true, birthday=null, maps=null, lists=null, dog=null}

**属性名匹配规则(Relaxed binding)

– person.firstName:使用标准方式

– person.first-name:大写用-

– person.first_name:大写用_

– PERSON_FIRST_NAME:

• 推荐系统属性使用这种写法**

配置文件注入值数据校验


@Value 不支持数据校验。

需要先在pom.xml引入校验的依赖:

org.springframework.boot

spring-boot-starter-validation

Person:(部分代码,get和set以及toString不展示了)

package com.keafmd.springboot.bean;

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

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

import org.springframework.context.annotation.PropertySource;

import org.springframework.stereotype.Component;

import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.Email;

import java.util.Date;

import java.util.List;

import java.util.Map;

/**

  • Keafmd

  • @ClassName: Person

  • @Description:

  • @author: 牛哄哄的柯南

  • @date: 2021-02-23 12:47

*/

/**

  • 将配置文件中配置的每一个属性的值,映射到这个组件中

  • @ConfigurationProperties :告诉SpringBoot将本类中的所有属性和配置文件相关的配置进行绑定

  • prefix = “person” :配置文件中哪个属性进行一一映射

  • 只有这个组件时容器中的组件吗,才能使用容器提供的功能

*/

@Component

@ConfigurationProperties(prefix = “person”)

@Validated //校验

public class Person {

/**

  • <property name = "lastName" value = "字面量/${key}从环境变量、配置文件中获取值/#{SpEL}"></property>
    

*/

//@Value(“${person.last-name}”)

//lastName必须是邮箱格式

@Email

private String lastName;

//@Value(“#{11*2}”)

private Integer age;

//@Value(“true”)

private Boolean boss;

private Date birthday;

private Map<String,Object> maps;

private List lists;

private Dog dog;

}

运行测试类的结果:

在这里插入图片描述

@PropertySource&@ImportResource&@Bean


@PropertySource:加载指定的配置文件

person.properties:

person.last-name=Keafmd-person

person.age=18

person.boss=false

person.birthday=2022/02/02

person.maps.k1=v1

person.maps.k2=v2

person.lists=a,b,c

person.dog.name=二狗

person.dog.age=3

我们想加载这个配置文件的内容,就必须用 @PropertySource指定配置文件

package com.keafmd.springboot.bean;

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

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

import org.springframework.context.annotation.PropertySource;

import org.springframework.stereotype.Component;

import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.Email;

import java.util.Date;

import java.util.List;

import java.util.Map;

/**

  • Keafmd

  • @ClassName: Person

  • @Description:

  • @author: 牛哄哄的柯南

  • @date: 2021-02-23 12:47

*/

/**

  • 将配置文件中配置的每一个属性的值,映射到这个组件中

  • @ConfigurationProperties :告诉SpringBoot将本类中的所有属性和配置文件相关的配置进行绑定

  • prefix = “person” :配置文件中哪个属性进行一一映射

  • 只有这个组件时容器中的组件吗,才能使用容器提供的功能

*/

@PropertySource(value = {“classpath:person.properties”})

@Component

@ConfigurationProperties(prefix = “person”)

//@Validated //校验

public class Person {

/**

  • <property name = "lastName" value = "字面量/${key}从环境变量、配置文件中获取值/#{SpEL}"></property>
    

*/

//@Value(“${person.last-name}”)

//lastName必须是邮箱格式

//@Email

private String lastName;

//@Value(“#{11*2}”)

private Integer age;

//@Value(“true”)

private Boolean boss;

private Date birthday;

private Map<String,Object> maps;

private List lists;

private Dog dog;

}

运行测试类的测试结果:

Person{lastName=‘Keafmd-person’, age=18, boss=false, birthday=Wed Feb 02 00:00:00 CST 2022, maps={k1=v1, k2=v2}, lists=[a, b, c], dog=Dog{name=‘二狗’, age=3}}

注意:需要把application.propertiesapplication.yml里的person注释掉。

@ImportResource:导入Spring的配置文件,让配置文件里面的内容生效,使用@Bean给容器中添加组件

**Spring Boot里面没有Spring的配置文件,我们自己编写的配置文件,也不能自动识别。

如果想让Spring的配置文件生效,加载进来,需要把@ImportResource标注在一个配置类上。**

@ImportResource(locations = {“classpath:beans.xml”})

导入Spring的配置文件让其生效

创建一个Spring的配置文件beans.xml

<?xml version="1.0" encoding="UTF-8"?>

<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”>

创建一个helloService:

package com.keafmd.springboot.service;

/**

  • Keafmd

  • @ClassName: HelloService

  • @Description:

  • @author: 牛哄哄的柯南

  • @date: 2021-02-23 15:59

*/

public class HelloService {

}

先测试下容器中有没有helloService:

package com.keafmd.springboot;

import com.keafmd.springboot.bean.Person;

import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.test.context.SpringBootTest;

import org.springframework.context.ApplicationContext;

/**

  • SpringBoot单元测试

  • 可以再测试期间很方便的类似编码一样进行自动注入等容器

*/

@SpringBootTest

class SpringBoot02ConfigApplicationTests {

@Autowired

Person person;

@Autowired

ApplicationContext ioc;

@Test

public void testHelloService(){

Boolean b = ioc.containsBean(“helloService”);

System.out.println(b);

}

@Test

public void contextLoads() {

System.out.println(person);

}

}

运行testHelloService的测试结果:

false

此时说明配置文件并没有生效。

我们把@ImportResource标注在主配置类上。

SpringBoot02ConfigApplication :

package com.keafmd.springboot;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.context.annotation.ImportResource;

@ImportResource(locations = {“classpath:beans.xml”})

@SpringBootApplication

public class SpringBoot02ConfigApplication {

public static void main(String[] args) {

SpringApplication.run(SpringBoot02ConfigApplication.class, args);

}

}

再次运行测试方法:

true

在这里插入图片描述

但是在实际开发中我们会采用一种更合适的方法,SpringBoot推荐给容器中添加组件的方式是推荐使用全注解的方式。接下来把@ImportResource(locations = {"classpath:beans.xml"})注释掉,创建一个配置类MyAppConfig 。

**1、创建配置类,使用 @Configuration ------>Spring配置文件

2、使用 @Bean给容器中添加组件**

==MyAppConfig: ==

package com.keafmd.springboot.config;

import com.keafmd.springboot.service.HelloService;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

/**

  • Keafmd

  • @ClassName: MyAppConfig

  • @Description: 配置类

  • @author: 牛哄哄的柯南

  • @date: 2021-02-23 16:06

*/

/**

  • @Configuration: 指明当前类是配置类,替代之前的Spring配置文件

  • 在配置文件中用标签添加组件

*/

@Configuration

public class MyAppConfig {

//将方法的返回值添加到容器中,容器中这个组件默认的id就是方法名

@Bean

public HelloService helloService(){

System.out.println(“配置类@Bean给容器添加组件了。。。”);

return new HelloService();

}

}

再次运行测试方法:

在这里插入图片描述

配置文件占位符

=================================================================

随机数


r a n d o m . v a l u e 、 {random.value}、 random.value{random.int}、${random.long}

r a n d o m . i n t ( 10 ) 、 {random.int(10)}、 random.int(10){random.int[1024,65536]}

占位符获取之前配置的值,如果没有可以是用:指定默认值


配置person的值

person.last-name=Keafmd${random.uuid}

#person.last-name=张三

#person.age=${random.int}

person.age=18

person.boss=false

person.birthday=2022/02/02

person.maps.k1=v1

person.maps.k2=v2

person.lists=a,b,c

#person.dog.name=${person.last-name}的二狗

person.dog.name=${person.hello:hello}的二狗

#person.dog.name=二狗

person.dog.age=3

Profile

=================================================================

多Profile文件


**我们在主配置文件编写的时候,文件名可以是 application-{profile}.properties/yml

默认使用application.properties的配置**

在这里插入图片描述

yml支持多文档块方式


server:

port: 8081

spring:

profiles:

active: dev #指定属于哪个环境


server:

port: 8083

spring:

config:

activate:

on-profile: dev


server:

port: 8084

spring:

profiles: prod #不推荐的写法


在这里插入图片描述

激活指定profile


​在配置文件中指定 spring.profiles.active=dev

application.properties:

server.port=8081

spring.profiles.active=dev

命令行

1、可以在这里配置

在这里插入图片描述

在这里插入图片描述

2、也可以直接在测试的时候,配置传入命令行参数

打包后运行jar包时,输入下面的命令:

最后

光给面试题不给答案不是我的风格。这里面的面试题也只是凤毛麟角,还有答案的话会极大的增加文章的篇幅,减少文章的可读性

Java面试宝典2021版

最常见Java面试题解析(2021最新版)

2021企业Java面试题精选

《一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码》点击传送门,即可获取!
荐的写法


在这里插入图片描述

激活指定profile


​在配置文件中指定 spring.profiles.active=dev

application.properties:

server.port=8081

spring.profiles.active=dev

命令行

1、可以在这里配置

在这里插入图片描述

在这里插入图片描述

2、也可以直接在测试的时候,配置传入命令行参数

打包后运行jar包时,输入下面的命令:

最后

光给面试题不给答案不是我的风格。这里面的面试题也只是凤毛麟角,还有答案的话会极大的增加文章的篇幅,减少文章的可读性

Java面试宝典2021版

[外链图片转存中…(img-KXY62KHa-1714758828832)]

[外链图片转存中…(img-rU8XGISQ-1714758828833)]

最常见Java面试题解析(2021最新版)

[外链图片转存中…(img-kI88r3aZ-1714758828833)]

[外链图片转存中…(img-fK6i9DGv-1714758828833)]

2021企业Java面试题精选

[外链图片转存中…(img-R5y12CfX-1714758828834)]

[外链图片转存中…(img-08Pvey1n-1714758828834)]

《一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码》点击传送门,即可获取!

  • 24
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值