二、SpringBoot的配置--bilibili雷丰阳笔记

2024-03-13 20:08

本文主要是介绍二、SpringBoot的配置--bilibili雷丰阳笔记,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1、配置文件

application.properties

application.yml

2、yml

字面量: 数字 字符串 布尔 中间有空格 不加双引号和单引号,双引号(不会转义特殊字符)和单引号(会转义)

k: v

对象:map

friends:lastName: zhangsanage: 20

行内写法

friends: {lastName: zhangsan,age: lisi}

数组:list set

用短横线-数组元素

pets:- cat- dog- pig

行内写法

pets: [cat,dog,pig]

项目

从配置文件获取值

application.yml

person:lastName: zhangsanage: 18boss: falsebirth: 2017/12/12maps: {k1: v1,k2: v2}lists:- lisi- zhangliudog:name: 小狗age: 12

javaBean

package com.it.springboot01helloworld.bean;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 {private String lastName;private Integer age;private boolean boss;private Date birth;private Map<String, Object> maps;private List<Object> lists;private Dog dog;@Overridepublic String toString() {return "Person{" +"lastName='" + lastName + '\'' +", age=" + age +", boss=" + boss +", birth=" + birth +", maps=" + maps +", lists=" + lists +", 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 isBoss() {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> getMaps() {return maps;}public void setMaps(Map<String, Object> maps) {this.maps = maps;}public List<Object> getLists() {return lists;}public void setLists(List<Object> lists) {this.lists = lists;}public Dog getDog() {return dog;}public void setDog(Dog dog) {this.dog = dog;}
}package com.it.springboot01helloworld.bean;public class Dog {private String name;private Integer age;@Overridepublic String toString() {return "Dog{" +"name='" + name + '\'' +", age=" + 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;}
}

pom 导入

        <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional></dependency>

测试

package com.it.springboot01helloworld;import com.it.springboot01helloworld.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 SpringBootApplicationTest {@AutowiredPerson person;@Testpublic void contextLoads(){System.out.println(person);}
}

application.properties文件

person.last-name=张三
person.age=12
person.birth=2017/12/15
person.boss=false
person.maps.k1=v1
person.maps.k2=v2
person.lists=a,b,c
person.dog.name=dog
person.dog.age=10

在这里插入图片描述

1.如果只需从配置文件获取一个值 @Value("${person.last-name}")

2.如果 javabean和配置文件进行映射 @ConfigurationProperties

3.@PropertySource和@ImportResource

@Component
@ConfigurationProperties(prefix = "person")
//@Validated
@PropertySource(value={"classpath:person.properties"})
public class Person {
//    @Emailprivate String lastName;private Integer age;private boolean boss;private Date birth;private Map<String, Object> maps;private List<Object> lists;private Dog dog;
}

@ImportResource 导入spring配置文件

@SpringBootApplication
@ImportResource(locations = {"classpath:beans.xml"})
public class SpringBoot01HelloworldApplication {public static void main(String[] args) {SpringApplication.run(SpringBoot01HelloworldApplication.class, args);}}/*** 在编码的时候进行容器注入*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootApplicationTest {@AutowiredPerson person;@AutowiredApplicationContext ioc;@Testpublic void testHelloService(){boolean b = ioc.containsBean("helloService");System.out.println(b);}@Testpublic void contextLoads(){System.out.println(person);}
}

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 id="helloService" class="com.it.springboot01helloworld.service.HelloService"></bean>
</beans>

4.Springboot推荐给容器添加组件

@Configuration
public class MyAppConfig {@Beanpublic HelloService helloService02(){System.out.println("配置类bean给容器添加组件了。。。");return new HelloService();}}

5.配置文件占位符

1.随机数

${random.value} 

2.占位符获取之前获得的值,如果没有可以用:获得默认值

person.last-name=李四${random.uuid}
person.age=12
person.birth=2017/12/15
person.boss=false
person.maps.k1=v1
person.maps.k2=v2
person.lists=a,b,c
person.dog.name=${person.last-name}${person.hello:hello}dog
person.dog.age=10

6.Profile

application-dev.properties

application-prod.properties

spring.profiles.active=dev

yml

server:port: 8090
spring:profiles:active: dev
---
server:port: 8083
spring:profiles: dev
---server:port: 8022
spring:profiles: prod

在启动application

Program arguments的时候添加

--spring.profiles.active=prod

VM options

-Dspring.profiles.active=prod

或者

java -jar filename.jar --spring.profiles.active=prod

7.添加项目背景

server.context-path=/boot

http://localhost:8022/boot/hello

8.还可以通过来改变默认文件的位置

–spring.config.location

项目打包以后,可以通过命令行参数的形式,启动项目来指定

java -jar filename.jar --server.port=8087 --server.context-path=/abc

配置项太多,直接将配置文件放到jar包的旁边

@EnableAutoConfiguration

解释自动配置原理 一个例子

@Configuration
@EnableConfigurationProperties({HttpEncodingProperties.class})
@ConditionalOnWebApplication
@ConditionalOnClass({CharacterEncodingFilter.class})
@ConditionalOnProperty(prefix = "spring.http.encoding",value = {"enabled"},matchIfMissing = true
)
public class HttpEncodingAutoConfiguration { 

所有配置文件的属性都在 xxxProperties中封装的

@ConfigurationProperties(prefix = "spring.http.encoding")
public class HttpEncodingProperties {public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

根据当前的不同条件判断,决定这个配置类是否生效

springboot会加重大量自动配置类

自动配置类配置了哪些组件

会从properties中获取属性

xxxAutoConfiguration

xxxProperties

idea快捷键 查找某个类

ctrl+shift+n *AutoConfiguration

条件判断类

@ConditionalOnClass(CharacterEncodingFilter.class)

自动配置类在一定条件下才会生效

配置文件 开启debug模式

debug=true

Positive matches:
-----------------DispatcherServletAutoConfiguration matched:- @ConditionalOnClass found required class 'org.springframework.web.servlet.DispatcherServlet'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)- @ConditionalOnWebApplication (required) found StandardServletEnvironment (OnWebApplicationCondition)DispatcherServletAutoConfiguration.DispatcherServletConfiguration matched:- @ConditionalOnClass found required class 'javax.servlet.ServletRegistration'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)- Default DispatcherServlet did not find dispatcher servlet beans (DispatcherServletAutoConfiguration.DefaultDispatcherServletCondition)Negative matches:
-----------------ActiveMQAutoConfiguration:Did not match:- @ConditionalOnClass did not find required classes 'javax.jms.ConnectionFactory', 'org.apache.activemq.ActiveMQConnectionFactory' (OnClassCondition)AopAutoConfiguration:Did not match:- @ConditionalOnClass did not find required classes 'org.aspectj.lang.annotation.Aspect', 'org.aspectj.lang.reflect.Advice' (OnClassCondition)

这篇关于二、SpringBoot的配置--bilibili雷丰阳笔记的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/806051

相关文章

IDEA中配置Tomcat全过程

《IDEA中配置Tomcat全过程》文章介绍了在IDEA中配置Tomcat的六步流程,包括添加服务器、配置部署选项、设置应用服务器及启动,并提及Maven依赖可能因约定大于配置导致问题,需检查依赖版本... 目录第一步第二步第三步第四步第五步第六步总结第一步选择这个方框第二步选择+号,找到Tomca

分布式锁在Spring Boot应用中的实现过程

《分布式锁在SpringBoot应用中的实现过程》文章介绍在SpringBoot中通过自定义Lock注解、LockAspect切面和RedisLockUtils工具类实现分布式锁,确保多实例并发操作... 目录Lock注解LockASPect切面RedisLockUtils工具类总结在现代微服务架构中,分布

Java使用Thumbnailator库实现图片处理与压缩功能

《Java使用Thumbnailator库实现图片处理与压缩功能》Thumbnailator是高性能Java图像处理库,支持缩放、旋转、水印添加、裁剪及格式转换,提供易用API和性能优化,适合Web应... 目录1. 图片处理库Thumbnailator介绍2. 基本和指定大小图片缩放功能2.1 图片缩放的

Win10安装Maven与环境变量配置过程

《Win10安装Maven与环境变量配置过程》本文介绍Maven的安装与配置方法,涵盖下载、环境变量设置、本地仓库及镜像配置,指导如何在IDEA中正确配置Maven,适用于Java及其他语言项目的构建... 目录Maven 是什么?一、下载二、安装三、配置环境四、验证测试五、配置本地仓库六、配置国内镜像地址

Spring Boot集成/输出/日志级别控制/持久化开发实践

《SpringBoot集成/输出/日志级别控制/持久化开发实践》SpringBoot默认集成Logback,支持灵活日志级别配置(INFO/DEBUG等),输出包含时间戳、级别、类名等信息,并可通过... 目录一、日志概述1.1、Spring Boot日志简介1.2、日志框架与默认配置1.3、日志的核心作用

破茧 JDBC:MyBatis 在 Spring Boot 中的轻量实践指南

《破茧JDBC:MyBatis在SpringBoot中的轻量实践指南》MyBatis是持久层框架,简化JDBC开发,通过接口+XML/注解实现数据访问,动态代理生成实现类,支持增删改查及参数... 目录一、什么是 MyBATis二、 MyBatis 入门2.1、创建项目2.2、配置数据库连接字符串2.3、入

Springboot项目启动失败提示找不到dao类的解决

《Springboot项目启动失败提示找不到dao类的解决》SpringBoot启动失败,因ProductServiceImpl未正确注入ProductDao,原因:Dao未注册为Bean,解决:在启... 目录错误描述原因解决方法总结***************************APPLICA编

深度解析Spring Security 中的 SecurityFilterChain核心功能

《深度解析SpringSecurity中的SecurityFilterChain核心功能》SecurityFilterChain通过组件化配置、类型安全路径匹配、多链协同三大特性,重构了Spri... 目录Spring Security 中的SecurityFilterChain深度解析一、Security

SpringBoot多环境配置数据读取方式

《SpringBoot多环境配置数据读取方式》SpringBoot通过环境隔离机制,支持properties/yaml/yml多格式配置,结合@Value、Environment和@Configura... 目录一、多环境配置的核心思路二、3种配置文件格式详解2.1 properties格式(传统格式)1.

Apache Ignite 与 Spring Boot 集成详细指南

《ApacheIgnite与SpringBoot集成详细指南》ApacheIgnite官方指南详解如何通过SpringBootStarter扩展实现自动配置,支持厚/轻客户端模式,简化Ign... 目录 一、背景:为什么需要这个集成? 二、两种集成方式(对应两种客户端模型) 三、方式一:自动配置 Thick