之前说了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 {
}