工控智汇

工控智汇

springboot:编写自己的starter,附源码

admin 128 162

我们使用springboot最突出的感受就是简单。springboot工程会依赖很多starter,starter整合了很多依赖配置,可以加快环境的搭建。


上面的starter依赖的jar和我们自己手动配置的时候依赖的jar并没有什么不同,所以我们可以认为starter其实是把这一些繁琐的配置操作交给了自己,而把简单交给了用户。除了帮助用户去除了繁琐的构建操作,在“约定大于配置”的理念下,ConfigurationProperties还帮助用户减少了无谓的配置操作。并且因为文件的存在,即使需要自定义配置,所有的配置也只需要在一个文件中进行,使用起来非常方便。

们也可以编写自己的starter。

1,创建一个maven工程

创建一个最基本的springboot工程。

2,创建一个Starter模块隶属于父项目3,创建配置类
;;;/***配置文件配置类*/@ConfigurationProperties(prefix="spring101")@DatapublicclassMyServiceProperties{/***username*/privateStringname;/***userage*Shouldbetween1and120*/privateIntegerage;/***determinetheserviceversionyouwantuse*/privateStringversion;}

这个类的作用是关联配置源(比如文件配置),使用@ConfigurationProperties注解标注我们的POJO告知注解我们配置的前缀即可。

4,创建一个我们要执行服务类
;;/***使用抽象类*演示,多版本选择*和客户端实现以覆盖*/publicabstractclassAbstractMyService{protectedStringword;publicAbstractMyService(Stringword){=word;}publicAbstractMyService(){this("Hello");}@AutowiredprotectedMyServicePropertiesproperties;publicabstractStringhello();}

;;;@Slf4j@ServicepublicclassMyStarterServiceV1extsAbstractMyService{publicMyStarterServiceV1(Stringword){super(word);("MyStarterServiceV1:可以在构造器里执行点什么");}publicMyStarterServiceV1(){}@OverridepublicStringhello(){("V1%s%s:%s!!",word,(),());}}
5,配置和服务关联起来
;;;;;;;@Configuration@EnableConfigurationProperties()@Slf4jpublicclassMyAutoConfiguration{@Bean//ConditionalOnMissingBean:当客户端没有自己实现的service时,使用默认实现@ConditionalOnMissingBean()//使用的控制条件@ConditionalOnProperty(prefix="spring101",name="version",havingValue="v1",matchIfMissing=true)MyStarterServiceV1getMyService(){returnnewMyStarterServiceV1("hello");}@Bean@ConditionalOnMissingBean()@ConditionalOnProperty(prefix="spring101",name="version",havingValue="v2")MyStarterServiceV2getMyV2Service(){returnnewMyStarterServiceV2("hello");}}

这个是关键的类。@ConditionalOnxxx是条件选择。很容易读懂。

比如@ConditionalOnMissingBean()是说客户端没有自己实现的MyStarterServiceV1类时,使用该默认配置。

@ConditionalOnProperty后面加了其他的使用条件

6,加一个配置文件


在resources/META-INF下加一个配置文件

内容是

=
7,mavencleaninstall一下8,测试

再新建一个测试工程。

在resources下建一个文件

;;;;;@Component@Slf4jpublicclassRunner1implementsCommandLineRunner{@AutowiredprivateAbstractMyServiceservice;@Overridepublicvoidrun(Stringargs){(());}}

源码地址