亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

自定義的Spring Boot starter如何設置自動配置注解

標簽:
SpringBoot

Spring Boot实战之定制自己的starter一文最后提到,触发Spring Boot的配置过程有两种方法:

  1. spring.factories:由Spring Boot触发探测classpath目录下的类,进行自动配置;
  2. @Enable*:有时需要由starter的用户触发查找自动配置文件的过程。

实战

  • 接着上篇文章的例子,首先将spring.factories中的内容注释掉
#org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
#com.test.bookpubstarter.dbcount.DbCountAutoConfiguration
  • 创建元注解(meta-annotation),即在db-count-starter/src/main/java/org/test/bookpubstarter/dbcount目录下新建EnableDbCounting.java文件。
package com.test.bookpubstarter.dbcount;

import org.springframework.context.annotation.Import;
import java.lang.annotation.*;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import(DbCountAutoConfiguration.class)
@Documented
public @interface EnableDbCounting {
}
  • 在BookPubApplication类中删去之前手动创建的DbCountRunner的spring bean,然后用*@EnableDbCounting*注解修饰BookPubApplication类。
package com.test.bookpub;

import com.test.bookpubstarter.dbcount.EnableDbCounting;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableDbCounting
public class BookPubApplication {
    public static void main(String[] args) {
        SpringApplication.run(BookPubApplication.class, args);
    }
}
  • 启动应用程序,设置日志级别为DEBUG

由starter的用户手动触发配置

可以看出我们自己定义的注解起作用了。如果没有spring.factories,那么在程序启动的时候Spring Boot的自动配置机制不会试图解析DbCountAutoConfiguration类。一般来说,@Component注解的作用范围就是在BookPubApplication所在的目录以及各个子目录,即com.test.bookpub.*,而DbCountAutoConfiguration是在org.test.bookpubstarter.dbcount目录下,因此不会被扫描到。

@EnableDbCounting注解通过*@Import(DbCountAutoConfiguration.class)*找到对应的配置类,因此通过用@EnableDbCounting修饰BookPubApplication,就是告诉Spring Boot在启动过程中要把DbCountAutoConfiguration加入到应用上下文中。

Spring Boot 1.x系列

點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
JAVA開發工程師
手記
粉絲
0
獲贊與收藏
10

關注作者,訂閱最新文章

閱讀免費教程

  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消