springboot学习笔记------配置

配置文件

配置文件

使用全局配置文件: application.properties application.yml(附小知识点: yml是YAML(YAML Ain’t Markup Language)语言的文件,以数据为中心,比json.xml更适合做配置文件)
配置文件位置: src/main/resources目录或者类路径/config
全局配置文件可以对一些默认设置值进行修改

YAML语法

参考我的这篇博客:
YAML语法

配置文件值注入

@Value和@ConfigurationProperties为属性注值

image.png | left | 747x127

松绑定

  • @ConfigurationProperties使用中,不必每个字都和配置中的key一致;批量注入配置文件属性
  • @Value必须要一致,只能一个个的进行绑定
  • 松散语法
- person.firstName:使用标准方式
- person.first-name:大写用-         
- person.first_name:大写用_
- PERSON_FIRST_NAME: 系统属性推荐使用这种写法

数据源支持

  • @ConfigurationProperties支持spring元数据,可以在resource下建立META-INF文件夹,建立文件additional-spring-configuration-metadata.json.里面数据格式必须满足spring元数据格式

SpEl

  • @ConfigurationProperties不支持EL表达式
  • eg: application.properties文件中有字段:person.userAge=12
userAge = 12   //可以
userAge = #{2*6}  //EL表达式不支持
  • @Value支持EL表达式
@Value(userAge=#{2*6}) //支持EL表达式

JSR303数据校验

  • @ConfigurationProperties @Validated支持 @Value不支持

使用原则

  • 某个业务逻辑需要获取配置文件某项值使用@Value. 专门编写javaBean和配置文件进行映射,可直接使用@ConfigurationProperties

@PropertySource使用

  • 加载指定路径的配置文件信息

image.png | left | 719x93

  • @ConfigurationProperties(prefix=”activiti”) 默认加载全局配置文件,application.properties和application.yml.全局配置文件中,有字段: activiti.first-name
  • @PropertySource,加载的指定路径的配置文件信息,就是读上图中路径配置文件

@ImportResource

  • 读取外部配置文件
@ImportResource(locations = {"applicationContext.xml"})

上面是以前的做法,springboot推荐做法是什么?

全注解

image.png | left | 747x166

  • @Configuration:指明当前类是一个配置类,替代了之前的spring配置文件
  • Spring容器启动时,默认加载一些postPRocessor,其中有ConfigurationClassPostProcessor,这个后置程序专门处理带有@Configuration注解的类,程序在bean定义加载完成后,在bean初始化前进行处理.

配置文件占位符

  • 可使用提供的一些随机数
${random.uuid}、${random.int}、${random.long}
${random.int(10)}、${random.int[1024,65536]}
  • 第一个取出来是随机数,第二个是整型,第三个是长整型;
  • 获取之前配置的值,如果没有使用: 指定默认值
person.last‐name=张三${random.uuid}
person.age=${random.int}
person.birth=2017/12/15
person.dog.name=${person.hello:hello}_dog

Profile多环境配置

  • 多profile文件形式
    • 格式:

image.png | left | 164x89

  • 多profile文档块模块

    • image.png | left | 537x263
  • 激活方式

    • 命令行–spring.profiles.active=dev
    • 配置文件spring.profiles.active=dev (jenkins构建指定,代码中这样写,见下图)

      • image.png | left | 390x92
    • jvm参数 -Dspring.profiles.active=dev

加载顺序

启动时扫描以下位置的application.properties或者application.yml文件作为默认配置文件
* file:./config/
* file:./
* classpath:/config/
* classpath:/
* 优先级从高到低,高优先级会覆盖低优先级内容
* 可通过配置spring.config.location改变默认配置

配置原理

image.png | left | 747x205

上图是springboot启动类,我们进入@SpringBootApplication. 在里面找到了@EnableAutoConfiguration

image.png | left | 747x162

@EnableAutoConfiguration通过@Import导入了AutoConfigurationImportSelector
找到selectImports方法,调用的是

image.png | left | 747x230

我们进入这个方法看:

image.png | left | 747x173

loadFactoryNames方法内部直接调用loadSpringFactories方法,loadSpringFactories方法调用方式

image.png | left | 747x84

不仅仅包含项目中,还包含项目环境所依赖的jar包中,所以看下图!

image.png | left | 747x386

这个文件里,可以看到一系列的springboot自动配置的列表
我们进入一个里面,看一下细节ElasticsearchAutoConfiguration

/*
 * Copyright 2012-2018 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.boot.autoconfigure.data.elasticsearch;

import java.util.Properties;

import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.client.TransportClientFactoryBean;

/**
 * {@link org.springframework.boot.autoconfigure.EnableAutoConfiguration
 * Auto-configuration} for Elasticsearch.
 *
 * @author Artur Konczak
 * @author Mohsin Husen
 * @author Andy Wilkinson
 * @since 1.1.0
 */
@Configuration
@ConditionalOnClass({ Client.class, TransportClientFactoryBean.class })
@ConditionalOnProperty(prefix = "spring.data.elasticsearch", name = "cluster-nodes", matchIfMissing = false)
@EnableConfigurationProperties(ElasticsearchProperties.class)
public class ElasticsearchAutoConfiguration {
    private final ElasticsearchProperties properties;
    public ElasticsearchAutoConfiguration(ElasticsearchProperties properties) {
        this.properties = properties;
    }
    @Bean
    @ConditionalOnMissingBean
    public TransportClient elasticsearchClient() throws Exception {
        TransportClientFactoryBean factory = new TransportClientFactoryBean();
        factory.setClusterNodes(this.properties.getClusterNodes());
        factory.setProperties(createProperties());
        factory.afterPropertiesSet();
        return factory.getObject();
    }
    private Properties createProperties() {
        Properties properties = new Properties();
        properties.put("cluster.name", this.properties.getClusterName());
        properties.putAll(this.properties.getProperties());
        return properties;
    }
}

声明了es所需的bean,依赖于springboot注释
@ConditionalOnClass 某个class位于类路径上,才会实例化成一个bean
@ConditionalOnMissingBean 判断是否执行初始化代码,即用户已经创建了bean,相关初始化代码不再执行

也可以使用自己的配置替代自动配置

猜你喜欢

转载自blog.csdn.net/kwy15732621629/article/details/81109776