編寫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")
查看@ConditionOnPropertyjava

@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.spring

最後咱們須要註冊本身的配置類

  • 在/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

相關文章
相關標籤/搜索