Spring boot 自定义Starter
1、pom依赖
<!-- 以下两个依赖是自动配置的依赖 -->
<!--这个包已经包括在spring-boot-starter中-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<!--这个依赖主要可以在代码中轻松的使用@ConfigurationProperties注解注入属性文件配置的属性值-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
2、定义自动配置类,例:
@Configuration
@ComponentScan(basePackages = {
"com.xx.xx.xx.service",
"com.xx.xx.xx.controller"})
@EntityScan(basePackages = "com.xx.xx.xx.domain")
@EnableDynamicQueryRepositories(basePackages = "com.xx.xx.xx.repository")
public class PrivilegeConfig {
//这里可以配置Bean定义
}
3、在src\main\resources\META-INF目录下添加spring.factories文件,例:
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.xx.xx.xx.autoconfigure.PrivilegeConfig
4、可以获取自定义的配置信息
starter是如何读取application.properties或者application.yml配置文件内需要的配置参数的呢? SpringBoot在处理这种事情上早就已经考虑到了,所以提供了一个注解@ConfigurationProperties。
因涉及内容较多,所以具体使用方式请自行百度
注意事项:
Spring Boot Application如果依赖这种有jpa扫描的Starter必须添加@EntityScan注解, 否则自己项目中的实体将不会被扫描到,相应repository实例化时也会出错,例:
@SpringBootApplication()
@EntityScan(basePackages = {"com.xx.xx.tester.entity"})
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class,args);
}
}
延伸知识
在构建starter的过程中,涉及到一些注解,这里也做一个统一的说明
@ConditionalOnBean:当容器中有指定的Bean的条件下
@ConditionalOnClass:当类路径下有指定的类的条件下
@ConditionalOnExpression:基于SpEL表达式作为判断条件
@ConditionalOnJava:基于JVM版本作为判断条件
@ConditionalOnJndi:在JNDI存在的条件下查找指定的位置
@ConditionalOnMissingBean:当容器中没有指定Bean的情况下
@ConditionalOnMissingClass:当类路径下没有指定的类的条件下
@ConditionalOnNotWebApplication:当前项目不是Web项目的条件下
@ConditionalOnProperty:指定的属性是否有指定的值
@ConditionalOnResource:类路径下是否有指定的资源
@ConditionalOnSingleCandidate:当指定的Bean在容器中只有一个,或者在有多个Bean的情况下,用来指定首选的Bean
@ConditionalOnWebApplication:当前项目是Web项目的条件下