编写Spring boot自动配置

背景

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

START


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

工具

  • IntelliJ IDEA 2018

步骤

1.创建一个普通的spring boot项目
创建项目
  • 注意其中的Group和Artifact,这两项将对应以后使用的依赖参数
<dependency>
            <groupId>xyz.crabapple</groupId>
            <artifactId>begonia</artifactId>
            <version>0.0.1-SNAPSHOT</version>
</dependency>
2.项目的目录结构
目录结构
3.现在我们主要代码需要写在begonia目录下
java代码
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文件.


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

END

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,084评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,623评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,450评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,322评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,370评论 6 390
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,274评论 1 300
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,126评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,980评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,414评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,599评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,773评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,470评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,080评论 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,713评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,852评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,865评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,689评论 2 354

推荐阅读更多精彩内容