SpringBoot学习笔记2

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

@ConfigurationProperties@Value
功能批量注入配置文件中的属性一个个绑定
松散绑定(松散语法)支持不支持
SPEL不支持支持
JSR303数据校验支持不支持
复杂类型分装支持不支持

@Value注解
配置文件yml或者properties他们都能获取到值;
如果说,我们只是在某个业务逻辑中的获取一下配置文件中的某项值,我们使用@Value。
如果说,我们专们编写了一个JavaBean来和配置文件进行映射,我们就直接使用ConfigurationProperties直接使用

2、 配置文件注入值数据校验

@Component//添加到容器中
@ConfigurationProperties(prefix = "person")
@Validated //数据校验
public class Person {
    /**
     * <bean class="person">
     *<property name="lastName" value="字面量/${key}从环境变量、配置文件获取值/#{SpEL}">
     *</property>
     * </bean>
     * @return
     */
//    @Value("${person.last-name}")
//    @Email//lastName 必须是邮箱格式,@Value不支持
    private String lastName;
//    @Value("#{11*2}")
    private Integer age;
//    @Value("true")
    private Boolean boss;
    private Date birth;
    private Map<String,Object> maps;
    private List<Object>lists;
    private Dog dog;

3、@PropertySource和@ImportResource

@PropertySource加载指定的配置文件

例如:
@PropertySource(value = “classpath:person.properties”)//加载制定的配置文件

@ImportResource导入Spring的配置文件,让配置文件里面的内容生效

Spring Boot 里面没有Sping配置文件,我们自己编写的配置文件也不能识别。想让Sping Boot 的配置文件生效,加载进来。;我们使用@ImportResource标注在一个配置类上

@ImportResource(locations = {"classpath:beans.xml"})//导入Sping 配置文件

不来编写Spring的配置文件

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

SpringBoot 推荐使用给容器添加组件的方式;推荐使用全注解的方式
1、配置类===Spring配置文件
2、使用@Bean给容器中添加组件

/**
 * 指明当前类是一个配置类,用来替代之前Spirng配置文件
 * 在配置文件中使用<Bean></Bean>标签来添加组件
 */
@Configuration
public class MyConfig {
    //将方法的返回值添加到容器中;容器中这个组件默认的id就是方法名
    @Bean
    public HelloService helloService(){
        System.out.println("配置类@Bean给容器添加组件");
        return new HelloService();
    }
}

4 、配置文件占位符

1、随机数
${random.value}   ${random.int}   ${random.long}
${random.int(10)}  ${random.int[1024,65536]}  
2、占位符获取之前配置的值,如果没有使用 获取默认值
person.dog.name=${person.last:hello}_dog 

5、profile

profile 是Spring对不同工作环境提供不同配置功能的支持,可以通过激活制定参数等方式快速切换环境

1、多Profile文件

我们在主配置文件编写的时候,文件名可以是application-{profile}.yml/properties
默认情况使用application.properties的配置

2、yml支持多文档块方法
server:
  port: 3333
spring:
  profiles:
    active: prod
---
server:
  port: 4444
spring:
  profiles: dev
---
server:
  port: 5555
spring:
  profiles: prod

6、激活指定profile

1、在配置文件中指定激活spring.profiles.active=dev
2、命令行方式

可以在配置的时候传入命令行参数

--spring.profiles.active=dev

java -jar demo-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev
在这里插入图片描述

3、虚拟机参数:

-Dspring.profiles.active=dev在这里插入图片描述

7、配置文件加载位置

springBoot会自动扫描以下位置的application.properties或者application.yml 文件作为Spring Boot 的默认配置文件

– file:./config/
– file:/
– classpath:/config
– classpath:/
优先级有高到低,高优先级的配置会覆盖低优先级的配置;
Spring Boot 会从四个位置全部加载主配置文件;互补配置
我们还可以通过使用spring.config.location来改变默认的配置文件位置
项目打包后以后,我们可以通过使用命令行参数的形式,启动项目的时候来指定项目的配置文件新位置;指定配置文件和默认加载配置文件共同起作用形成互补配置

8、 外部配置加载顺序

Spring Boot 可以从以下位置加载配置,优先级从高到低;高优先级的配置覆盖低优先级的配置;所有的配置会形成互补配置!!
1、命令行参数
java -jar demo-0.0.1-SNAPSHOT.jar --server.port=1771
多个参数用空格隔开
java -jar demo-0.0.1-SNAPSHOT.jar --server.port=1771 --server.servlet.context-path=/test
2、来自java:comp/env的NDI属性
3、Java系统属性(System.getProperties())
4、操作系统环境变量
5、RandomValuePropertySource配置的random.*属性值

由jar包外向jar内进行寻找
优先加载带profile的
6、jar包外部的application-{profile}.properties 或application-{profile}.yml(带spring.profile)配置文件
7、jar包内部的application-{profile}.properties 或application-{profile}.yml(带spring.profile)配置文件
再来加载不带profile的
8、jar包外部的application.properties 或application.yml(不带spring.profile)配置文件
9、jar包内部的application.properties 或application.yml(不带spring.profile)配置文件
10、@Configurtion注解类上的PropertySource
11、通过SpringApplication.setDefaultProperties指定文件

9、自动配置原理
配置文件能配置的属性参照官方文档
自动配置原理:

1、SpringBoot启动的时候加载主配置类,开启了自动配置功能 @EnableAutoConfiguration
1.1、@EnableAutoConfiguration作用:

利用AutoConfigurationImportSelector给容器中导入一些组件 可以使用selectImports ()方法的内容

List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);//获取候选的配置
SpringFactoriesLoader.loadFactoryNames
//扫描所有jar包类路径的 META-INF/spring.factories
把扫描到的这些文件的内容分装成properties对象
从properties中获取到EnableAutoConfiguration.class类(类名)对应的值,然后把他们添加到容器中

将类路径下META-INF/spring.factories里面配置的所有EnableAutoConfiguration的值加入到容器中;
每一个xxAutoConfiguration类都是容器中的一个组件,都加入到容器中;用他们来做自动配置;

1.2每一个自动配置类进行自动配置功能
1.3以HttpEncodingAutoConfiguration(HTTP的编码自动配置)为例解释自动配置原理
@Configuration(
    proxyBeanMethods = false
)
//表示这是一个配置类,和以前编写的配置文件一样,也可以给容器添加组件;将配置文件中对应的值和ServerProperties.class进行绑定起来
@EnableConfigurationProperties({ServerProperties.class})
//启用指定类的ConfigurationProperties功能,并把ServerProperties加入到ioc容器中
@ConditionalOnWebApplication(
    type = Type.SERVLET
)
//Spring底层有一个@Conditional注解,根据不同的条件,如果满足指定的条件,整个配置类里面的配置才会生效
//判断当前应用是否是web应用,如果是当前配置类生效
@ConditionalOnClass({CharacterEncodingFilter.class})
//判断当前项目有没有CharacterEncodingFilter类;CharacterEncodingFilter是在SpringMVC中进行乱码解决的拦截器
@ConditionalOnProperty(
    prefix = "server.servlet.encoding",
    value = {"enabled"},
    matchIfMissing = true
)
//判断配置文件是否存在某个配置 server.servlet.encoding.enabled;如果不存在判断也是成立的;
//即时配置文件中不配置server.servlet.encoding.enabled=true 也是默认生效的
public class HttpEncodingAutoConfiguration {
//他已经和springboot的配置文件映射
    private final Encoding properties;
//只有一个有参构造器的情况下,参数的值就会从容器中拿
    public HttpEncodingAutoConfiguration(ServerProperties properties) {
        this.properties = properties.getServlet().getEncoding();
    }

    @Bean//给容器中添加一个组件,这个组件的某些值要通过properties获取
    @ConditionalOnMissingBean
    public CharacterEncodingFilter characterEncodingFilter() {
        CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
        filter.setEncoding(this.properties.getCharset().name());
        filter.setForceRequestEncoding(this.properties.shouldForce(org.springframework.boot.web.servlet.server.Encoding.Type.REQUEST));
        filter.setForceResponseEncoding(this.properties.shouldForce(org.springframework.boot.web.servlet.server.Encoding.Type.RESPONSE));
        return filter;
    }

根据当前不同的条件判断,决定这个配置类是否生效?
一旦这个配置类生效,这个配置类就会给容器添加添加各种组件;这些组件的属性是对应的properties类获取。这些类里面的属性又是和配置文件绑定的;

1.4所有配置文件中能配置的属性都是在xxproperties类中封装;配置文件能配置什么就可以参照某个功能对应的这个属性类
@ConfigurationProperties(
    prefix = "server",
    ignoreUnknownFields = true
)//从配置文件中获取指定的值和Bean属性进行绑定

!!!精髓!!!

1、springboot启动会加载大量的自动配置类
2、我们看我们需要的功能有没有SpringBoot 写好的配置类;
3、我们再来看这个自动配置类到底配置了那些组件;(只要我们要用的组件有,我们就不需要再来配置了)
4、给容器中自动配置类添加组件的时候,会从properties中获取某些属性。我们就可以在配置文件中指定这些文件的值。
xxxAutoConfigurartion:自动配置类;
给容器中添加组件
xxxProperties:封装配置文件中相关属性值

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值