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 {
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值