编写Spring boot自动配置

流浪地球
• 阅读 2810

背景

  • 学习spring boot的自动配置对于了解整个后端代码运行流程非常重要,只有在了解spring boot是如何配置的情况下,才能在项目的配置中不那么举步维艰.

START


  • 假如我们编写了一个用于处理文件信息的工具类,那么我们可以如下操作

工具

  • IntelliJ IDEA 2018

步骤

1.创建一个普通的spring boot项目

编写Spring boot自动配置

  • 注意其中的Group和Artifact,这两项将对应以后使用的依赖参数
<dependency>
            <groupId>xyz.crabapple</groupId>
            <artifactId>begonia</artifactId>
            <version>0.0.1-SNAPSHOT</version>
</dependency>
2.项目的目录结构

编写Spring boot自动配置

3.现在我们主要代码需要写在begonia目录下

编写Spring boot自动配置

4.代码解释
  • BegoniaApplication 为spring boot自己生成的入口类所在的java文件.
  • Tool 是我的工具类具体实现
public class Tool {
    public String prefix;
    public Tool(String prefix) {
        this.prefix = prefix;
    }
    /**
     * 计算时间戳
     * @return 时间戳+五位随机大写字母
     */
    public  String getStamp() {
        String prefix = String.valueOf(new Date().getTime());
        prefix=prefix.substring(2,prefix.length());
        char[] arr = new char[5];
        Random random = new Random();
        for (int i = 0; i < 5; i++)
            arr[i] = (char) (65 + random.nextInt(26));
        String Suffix = String.valueOf(arr);
        return prefix + Suffix;
    }
  • ToolProperties充当配置类和application.properties的桥,即它从application.properties中取具体的配置信息,而真正的配置类需要再到ToolProperties去取.
@ConfigurationProperties(prefix = "Tool")
public class ToolProperties {
   private String prefix;

    public String getPrefix() {
        return prefix;
    }

    public void setPrefix(String path) {
        this.prefix = path;
    }
}
  • ToolAutoConfiguration是我的具体配置类
@Configuration
@EnableConfigurationProperties(ToolProperties.class)
@ConditionalOnClass(Tool.class)
@ConditionalOnProperty(prefix = "Tool", name="open" ,havingValue="true")
public class ToolAutoConfiguration {
    @Autowired
    ToolProperties toolProperties;
    @Bean
    public Tool autoConfiger(){
        System.out.println("Tool工具已启动");
        System.out.println(toolProperties.getPrefix());
        return new Tool(toolProperties.getPrefix());
    }
}

1.@Configuration 表示这是一个配置类,作用等同于@Component.
以下三个注解都是条件注解,如果有一个不满足条件,自动配置就不会运行.
2.@EnableConfigurationProperties(ToolProperties.class)
表示配置类的自动配置必须要求ToolProperties.class的存在
3.@ConditionalOnClass(Tool.class)
要求功能类存在.
4.@ConditionalOnProperty(prefix = "Tool", name="open" ,havingValue="true")
查看@ConditionOnProperty

@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
@Documented
@Conditional(OnPropertyCondition.class)
public @interface ConditionalOnProperty {

    /**
     * Alias for {@link #name()}.
     * @return the names
     */
    String[] value() default {};

    /**
     * A prefix that should be applied to each property. The prefix automatically ends
     * with a dot if not specified.
     * @return the prefix
     */
    String prefix() default "";

    /**
     * The name of the properties to test. If a prefix has been defined, it is applied to
     * compute the full key of each property. For instance if the prefix is
     * {@code app.config} and one value is {@code my-value}, the fully key would be
     * {@code app.config.my-value}
     * <p>
     * Use the dashed notation to specify each property, that is all lower case with a "-"
     * to separate words (e.g. {@code my-long-property}).
     * @return the names
     */
    String[] name() default {};

    /**
     * The string representation of the expected value for the properties. If not
     * specified, the property must <strong>not</strong> be equals to {@code false}.
     * @return the expected value
     */
    String havingValue() default "";

    /**
     * Specify if the condition should match if the property is not set. Defaults to
     * {@code false}.
     * @return if should match if the property is missing
     */
    boolean matchIfMissing() default false;

    /**
     * If relaxed names should be checked. Defaults to {@code true}.
     * @return if relaxed names are used
     */
    boolean relaxedNames() default true;

}

prefix和name拼凑起来表示application.properties的配置信息key,例如我的配置信息为Tool.open=true,那么@ConditionalOnProperty(prefix = "Tool", name="open" ,havingValue="true")就表示配置信息中有这个key就为true,即满足条件,在此条件下若等于注解中havingValue的值,则该注解最终的结果为true.

最后我们需要注册自己的配置类

  • 在/src/main目录下创建META-INF目录,并其下创建spring.factories文件,其实spring.factories文件就是一个.properties文件.

编写Spring boot自动配置

  • 新建好后,在其中按如下方式书写
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  xyz.crabapple.begonia.ToolAutoConfiguration
  1. 第一行的org.springframework.boot.autoconfigure.EnableAutoConfiguration就是一个key,第二行的xyz.crabapple.begonia.ToolAutoConfiguration就是我们的自动配置类,即value.配置类还可以按需添加.例如我们找一个依赖看一看
  2. 找到一个spring boot自带的依赖,可以看到其书写方式,供大家参考.
# Initializers
org.springframework.context.ApplicationContextInitializer=\
org.springframework.boot.autoconfigure.SharedMetadataReaderFactoryContextInitializer,\
org.springframework.boot.autoconfigure.logging.AutoConfigurationReportLoggingInitializer

END

点赞
收藏
评论区
推荐文章
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
美凌格栋栋酱 美凌格栋栋酱
7个月前
Oracle 分组与拼接字符串同时使用
SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Easter79 Easter79
3年前
spring注解
随着越来越多地使用Springboot敏捷开发,更多地使用注解配置Spring,而不是Spring的applicationContext.xml文件。Configuration注解:Spring解析为配置类,相当于spring配置文件Bean注解:容器注册Bean组件,默认id为方法名@Configurat
Easter79 Easter79
3年前
springboot操作redis基础说明
软件环境:springboot1.5.2,redis3.2.1配置在application.properties,增加redis的配置,主要配置项包括redis的ip,端口,密码等,具体如下:\redisRedis数据库索引(默认为0)spring.redis.database0Redis服务器地址spring
Easter79 Easter79
3年前
springboot整合mybatis+oracle
第一步认识springboot:springboot是为了解决配置文件多,各个组件不统一的问题,它省去了很多配置文件,同时实现了spring产品的整合。创建springboot项目:通过选择springinit初始化springboot,我们发现它的pom.xml拥有绝大部分的spring所需要的包。第二步_打开项目的结构,
Stella981 Stella981
3年前
Spring Boot 2.3 新特配置文件属性跟踪
背景当我们使用springboot在多环境打包,配置属性在不同环境的值不同,如下:spring:profiles:active:@project.profile@根据maven动态配置profilespring:profiles:devd
Stella981 Stella981
3年前
Spring Boot自动配置原理、实战
SpringBoot自动配置原理SpringBoot的自动配置注解是@EnableAutoConfiguration,从上面的@Import的类可以找到下面自动加载自动配置的映射。1.org.springframework.core.io.support.SpringFactoriesLoader.lo
Wesley13 Wesley13
3年前
FLV文件格式
1.        FLV文件对齐方式FLV文件以大端对齐方式存放多字节整型。如存放数字无符号16位的数字300(0x012C),那么在FLV文件中存放的顺序是:|0x01|0x2C|。如果是无符号32位数字300(0x0000012C),那么在FLV文件中的存放顺序是:|0x00|0x00|0x00|0x01|0x2C。2.  
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Easter79 Easter79
3年前
Springboot启动扩展点超详细总结,再也不怕面试官问了
1.背景Spring的核心思想就是容器,当容器refresh的时候,外部看上去风平浪静,其实内部则是一片惊涛骇浪,汪洋一片。Springboot更是封装了Spring,遵循约定大于配置,加上自动装配的机制。很多时候我们只要引用了一个依赖,几乎是零配置就能完成一个功能的装配。我非常喜欢这种自动装配的机制,所以在自己开发中间件和公共依赖工具的时