背景

  • 学习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.配置类还可以按需添加.例如我们找一个依赖看一看
  2. 找到一个spring boot自带的依赖,可以看到其书写方式,供大家参考.
# Initializers
org.springframework.context.ApplicationContextInitializer=\
org.springframework.boot.autoconfigure.SharedMetadataReaderFactoryContextInitializer,\
org.springframework.boot.autoconfigure.logging.AutoConfigurationReportLoggingInitializer

END


赵栩彬
358 声望600 粉丝

愿,你在遭受打击时,记起你的珍贵,抵抗恶意;