SpringBoot学习笔记-2:第二章 Spring Boot 配置

简介: SpringBoot学习笔记-2:第二章 Spring Boot 配置

第二章 Spring Boot 配置

1、YAML 配置

SpringBoot 全局配置文件


application.properties
application.yml

YAML 以数据为中心,比 json、xml 更适合作为配置文件


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

2、YAML 语法

https://yaml.org/


YAML 语言教程:


http://www.ruanyifeng.com/blog/2016/07/yaml.html


1、基本语法


key:空格value

空格缩进来控制层级关系,左对齐的数据就是一个层级

属性和值大小写敏感

空格必须有

2、值的写法

2.1、字面量:普通的值(数字,字符串,布尔)


字符串默认不用加单引号或者双引号


(1)""双引号不会转义特殊字符。特殊字符会作为本身想表达的意思

eg:


name: "张三\n李四"
输出:
张三[换行]
李四

(2)’'单引号,会转义特殊字符,特殊字符最终只是一个普通的字符串数据

eg:


name: "张三\n李四"
输出:
张三\n李四

2.2、对象,map(属性和值,键值对)


(1)普通写法


person:
  name: Tom
  age: 23

(2)行内写法


person: { name: Tom, age: 23 }

2.3、数组,(List, Set)


(1)普通写法


pets:
  - cat
  - dog
  - pig

(2)行内写法


pets: [cat, dog, pig]

3、YAML 配置文件中值获取

配置文件


src/main/resources/application.yml


person:
  lastName: Tom
  age: 18
  boss: false
  birth: 2017/12/12
  maps: { k1: v1, k2: v2 }
  lists:
    - cat
    - dog
  dog:
    name: Jack
    age: 2

映射类


src/main/java/com/mouday/bean/Person.java


 
         

src/main/java/com/mouday/bean/Dog.java


package com.mouday.bean;
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 +
                '}';
    }
}

单元测试依赖


pom.xml


<!--配置文件处理器 导入配置文件导入提示-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

单元测试


src/test/java/com/mouday/DemoApplicationTests.java


package com.mouday;
import com.mouday.bean.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;
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
    @Autowired
    private Person person;
    @Test
    public void contextLoads() {
        System.out.println(person);
    }
}

打印结果


Person{name='Tom', age=18, sex=false, birth=Tue Dec 12 00:00:00 CST 2017,
    maps={k1=v1, k2=v2},
    lists=[cat, dog],
    dog=Dog{name='Jack', age=2}
}

读取 properties 文件配置


src/main/resources/application.properties


person.name=TOM
person.age=18
person.sex=false
person.birth=2017/12/12
person.maps.k1=v1
person.maps.k2=v2
person.lists=cat,dog
person.dog.name=Jack
person.dog.age=2

4、@ConfigurationProperties 与@Value 区别


image.png

image.png

属性名匹配规则


person.firstName
person.first-name
person.first_name
PERSON_FIRST_NAME
package com.mouday.bean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
 * 将配置文件中的属性映射到这个组件中
 */
@Component
// @ConfigurationProperties(prefix = "person")
public class Person {
    /**
     * <bean class="Person">
     *     <property name="name" value="Tom" />
     * </bean>
     *
     * value 支持
     * 字面量
     * ${key}从环境变量,配置文件中获取值
     * #{SpEL}表达式
     */
    @Value("Tom")
    private String name;
    @Value("#{12*2}")
    private Integer age;
    @Value("true")
    private Boolean sex;
    @Value("${person.birth}")
    private Date birth;
    private Map<String, Object> maps;
    private List<String> lists;
    private Dog dog;
    /**
    * 略setter/getter toString()
    */
}

打印结果


Person{name='Tom', age=24, sex=true, birth=Tue Dec 12 00:00:00 CST 2017,
maps=null, lists=null, dog=null}

配置文件注入值数据校验


import org.hibernate.validator.constraints.Email;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
@Component
@ConfigurationProperties(prefix = "person")
@Validated
public class Person {
    @Email
    private String name;
}

使用方式


只是在某个业务逻辑中获取一个配置文件中的某项值,使用@Value

专门编写一个 javaBean 来映射配置文件,那么使用@ConfigurationProperties

@Value 用法示例


package com.mouday.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@Controller
@RestController
public class HelloController {
    @Value("${person.name}")
    private String name;
    @RequestMapping("/hello")
    @ResponseBody
    public String hello(){
        return "Hello world! " + this.name;
    }
}

5、@PropertySource、@ImportResource、@Bean

@ConfigurationProperties 默认加载全局配置


5.1、@PropertySource 加载指定配置文件


import org.springframework.stereotype.Component;
import org.springframework.context.annotation.PropertySource;
@Component
// @ConfigurationProperties(prefix = "person")
@PropertySource(value = {"classpath:person.properties"})
public class Person {}

5.2、@ImportResource 导入 Spring 配置文件


src/main/resources/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">
    <bean name="dog" class="com.mouday.bean.Dog"/>
</beans>

@ImportResource 标注在配置类上


package com.mouday;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
@ImportResource(value = {"classpath:beans.xml"})
@SpringBootApplication
public class ApplicationMain {
    public static void main(String[] args) {
        SpringApplication.run(ApplicationMain.class, args);
    }
}

测试方法


package com.mouday;
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.context.ApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
    @Autowired
    private ApplicationContext context;
    @Test
    public void TestDog(){
        System.out.println(this.context.containsBean("dog"));
    }
}

5.3、@Bean 用于配置类中给容器添加组件


package com.mouday.config;
import com.mouday.bean.Dog;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
 * @Configuration 指明当前类是一个配置类
 * 替代Spring的配置文件
 */
@Configuration
public class MyConfig {
    // 将方法的返回值添加到容器,容器中组件默认id是方法名
    @Bean
    public Dog dog(){
        return new Dog();
    }
}

Spring 推荐使用全注解方式给容器添加组件


6、配置文件占位符

RandomValuePropertySource 配置文件中可以使用随机数


${random.value}
${random.int}
${random.uuid}
${random.long}
${random.int(10)}
${random.int[1024,65536]}

属性配置占位符


app.name=MyApp
app.description=${app.name:默认值}

7、Profile 多环境支持

Profile 对不同环境提供不同配置功能的支持


1、多 Profile 文件


application-{profile}.properties


默认使用

application.properties

通过 spring.profiles.active=prod 指定配置文件


eg:

application.properties


server.port=8080
spring.profiles.active=prod

application-dev.properties


server.port=8081

application-prod.properties


server.port=8082

2、yaml 文档块模式


application.yml


server:
  port: 8080
spring:
  profiles:
    active: dev
---
server:
  port: 8081
spring:
  profiles: dev
---
server:
  port: 8082
spring:
  profiles: prod

3、激活方式

1、命令行
--spring.profiles.active=dev
2、配置文件
spring.profiles.active=dev
3、jvm参数
-Dspring.profiles.active=dev

8、配置文件的加载位置

Spring Boot 会自动扫描一下位置的

application.properties 或者 application.yml 文件作为配置文件


优先级从高到低,所有文件都被加载,


互补配置:高优先级覆盖低优先级


.

/config/
./
classpath:/config/
classpath:/

spring.config.location 修改默认位置


9、外部配置加载顺序

优先级从高到低如下


1. 命令行参数
$ java -jar springboot-helloword-1.0-SNAPSHOT.jar --server.port=8005
2. java:comp/env的JNDI属性
3. java系统属性System.getProperties()
4. 操作系统环境变量
5. RandomValuePropertySource配置的random.*属性
6. jar包外部的application-{profile}.properties或application.yml(带spring.profile)配置文件
7. jar包内部的application-{profile}.properties或application.yml(带spring.profile)配置文件
8. jar包外部的application.properties或application.yml(不带spring.profile)配置文件
9. jar包内部的application.properties或application.yml(不带spring.profile)配置文件
10. @Configuration注解类上的@PropertySource
11. 通过SpringApplication.setDefualtProperties指定的默认属性

总结:


高优先级配置会覆盖低优先级配置

所有配置会形成互补配置

10、自动配置原理

扫描配置文件内容包装成 properties 对象


将配置内容加载到容器中


AutoConfiguration 自动配置类

Properties 封装属性

@Condition 判断条件成立,决定配置类是否生效

11、@Conditional&自动配置报告

@ConditionalOnJava
@ConditionalOnMissingBean
@ConditionalOnClass
...

自动配置类必须在一定的条件下才生效


开启调试模式


debug=true

打印自动配置报告

=========================
AUTO-CONFIGURATION REPORT
=========================
Positive matches: 启动的自动配置类
Negative matches: 没启用启动的自动配置类
Exclusions:
Unconditional classes:

相关文章
|
2月前
|
Java Spring
Spring Boot配置的优先级?
在Spring Boot项目中,配置可通过配置文件和外部配置实现。支持的配置文件包括application.properties、application.yml和application.yaml,优先级依次降低。外部配置常用方式有Java系统属性(如-Dserver.port=9001)和命令行参数(如--server.port=10010),其中命令行参数优先级高于系统属性。整体优先级顺序为:命令行参数 &gt; Java系统属性 &gt; application.properties &gt; application.yml &gt; application.yaml。
471 0
|
5月前
|
安全 Java API
深入解析 Spring Security 配置中的 CSRF 启用与 requestMatchers 报错问题
本文深入解析了Spring Security配置中CSRF启用与`requestMatchers`报错的常见问题。针对CSRF,指出默认已启用,无需调用`enable()`,只需移除`disable()`即可恢复。对于`requestMatchers`多路径匹配报错,分析了Spring Security 6.x中方法签名的变化,并提供了三种解决方案:分次调用、自定义匹配器及降级使用`antMatchers()`。最后提醒开发者关注版本兼容性,确保升级平稳过渡。
626 2
|
1月前
|
安全 算法 Java
在Spring Boot中应用Jasypt以加密配置信息。
通过以上步骤,可以在Spring Boot应用中有效地利用Jasypt对配置信息进行加密,这样即使配置文件被泄露,其中的敏感信息也不会直接暴露给攻击者。这是一种在不牺牲操作复杂度的情况下提升应用安全性的简便方法。
552 10
|
6月前
|
安全 Java Apache
微服务——SpringBoot使用归纳——Spring Boot中集成 Shiro——Shiro 身份和权限认证
本文介绍了 Apache Shiro 的身份认证与权限认证机制。在身份认证部分,分析了 Shiro 的认证流程,包括应用程序调用 `Subject.login(token)` 方法、SecurityManager 接管认证以及通过 Realm 进行具体的安全验证。权限认证部分阐述了权限(permission)、角色(role)和用户(user)三者的关系,其中用户可拥有多个角色,角色则对应不同的权限组合,例如普通用户仅能查看或添加信息,而管理员可执行所有操作。
297 0
|
6月前
|
安全 Java 数据安全/隐私保护
微服务——SpringBoot使用归纳——Spring Boot中集成 Shiro——Shiro 三大核心组件
本课程介绍如何在Spring Boot中集成Shiro框架,主要讲解Shiro的认证与授权功能。Shiro是一个简单易用的Java安全框架,用于认证、授权、加密和会话管理等。其核心组件包括Subject(认证主体)、SecurityManager(安全管理员)和Realm(域)。Subject负责身份认证,包含Principals(身份)和Credentials(凭证);SecurityManager是架构核心,协调内部组件运作;Realm则是连接Shiro与应用数据的桥梁,用于访问用户账户及权限信息。通过学习,您将掌握Shiro的基本原理及其在项目中的应用。
231 0
|
2月前
|
人工智能 安全 Java
Spring Boot yml 配置敏感信息加密
本文介绍了如何在 Spring Boot 项目中使用 Jasypt 实现配置文件加密,包含添加依赖、配置密钥、生成加密值、在配置中使用加密值及验证步骤,并提供了注意事项,确保敏感信息的安全管理。
694 1
|
2月前
|
SQL XML Java
配置Spring框架以连接SQL Server数据库
最后,需要集成Spring配置到应用中,这通常在 `main`方法或者Spring Boot的应用配置类中通过加载XML配置或使用注解来实现。
218 0
|
5月前
|
Java Spring
Spring框架的学习与应用
总的来说,Spring框架是Java开发中的一把强大的工具。通过理解其核心概念,通过实践来学习和掌握,你可以充分利用Spring框架的强大功能,提高你的开发效率和代码质量。
141 20
|
6月前
|
消息中间件 存储 Java
微服务——SpringBoot使用归纳——Spring Boot中集成ActiveMQ——ActiveMQ安装
本教程介绍ActiveMQ的安装与基本使用。首先从官网下载apache-activemq-5.15.3版本,解压后即可完成安装,非常便捷。启动时进入解压目录下的bin文件夹,根据系统选择win32或win64,运行activemq.bat启动服务。通过浏览器访问`http://127.0.0.1:8161/admin/`可进入管理界面,默认用户名密码为admin/admin。ActiveMQ支持两种消息模式:点对点(Queue)和发布/订阅(Topic)。前者确保每条消息仅被一个消费者消费,后者允许多个消费者同时接收相同消息。
172 0
微服务——SpringBoot使用归纳——Spring Boot中集成ActiveMQ——ActiveMQ安装
|
6月前
|
消息中间件 Java 微服务
微服务——SpringBoot使用归纳——Spring Boot中集成ActiveMQ——发布/订阅消息的生产和消费
本文详细讲解了Spring Boot中ActiveMQ的发布/订阅消息机制,包括消息生产和消费的具体实现方式。生产端通过`sendMessage`方法发送订阅消息,消费端则需配置`application.yml`或自定义工厂以支持topic消息监听。为解决点对点与发布/订阅消息兼容问题,可通过设置`containerFactory`实现两者共存。最后,文章还提供了测试方法及总结,帮助读者掌握ActiveMQ在异步消息处理中的应用。
246 0