Springboot 自定義starter

之前說了SpringBoot的自動配置原理,現在說說一個簡單的自定義spring-boot-stater,這個starter的功能很簡單,就是沒200毫秒在控制檯輸出當前時間,要注意的是這個spring-boot-stater是一個獨立的模塊,與我們自己的spring-boot項目只需要用一個註解接口生效,取消這個註解,那麼這個功能也就沒了,功能描述完了,接下來我們看看代碼實現:

首先定義一個配置類,因爲這只是一個測試樣例,爲了減少類,所以這個配置也提供獲取當前時間的業務功能

@Configuration
@ComponentScan(basePackages = "org.springframework.boot.time")
@ConfigurationProperties(prefix = "mjlf", ignoreUnknownFields = false)
@Data
public class PatternConfig {

	private String format;// = "yyyy-MM-dd HH:mm:ss";

	public String nowTime(){
		LocalDateTime localDateTime = LocalDateTime.now();
		return localDateTime.format(DateTimeFormatter.ofPattern(this.format));
	}
}

然後提供時間打印類,由於是程序啓動制動執行,所以我們在這裏利用spring的生命週期回調實現,

@Component
public class ShowTime {

	@Autowired
	private PatternConfig pattern;

	@PostConstruct
	public void startShowTime(){
		new Thread(new Runnable() {
			@Override
			public void run() {
				while(true){
					try {
						Thread.currentThread().sleep(200);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println(pattern.nowTime());
				}
			}
		}).start();

	}
}

最後提供一個註解類,這個類是與外交進行溝通的橋樑,說在這個註解中,我們需要使用@Import導入我們的配置類,這樣當我們將這個註解標註在spring-boot項目上的使用,這個starter的配置類也會別加載爲congfigurationClass,其實這個原理與SpringBoot的@SpringBootApplication一樣,都是爲了引入配置類,而springboot內部通過一個配置文件,利用類SPI協議實現

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(PatternConfig.class)
public @interface EnableShowTime {
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章