# springboot-learn **Repository Path**: serain/springboot-learn ## Basic Information - **Project Name**: springboot-learn - **Description**: SpringBoot学习交流项目 - **Primary Language**: Java - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2018-09-04 - **Last Updated**: 2020-12-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # SpringBoot示例项目列表 > 所有项目基于SpringBoot2构建 * springboot-introduction 最简单的一个入门例子 * example ExampleService接口及实现 * example-springboot-starter 基于配置文件中某个配置项(在这里是example.service.enabled)启用的方式 * example-springboot-starter-demo 基于配置文件启用的方式,使用示例 * example-annocation-springboot-starter 基于注解启用的方式 * example-annocation-springboot-starter-demo 基于配置文件启用的方式,使用示例 * springboot-jpa-with-h2-unit-test 演示springboot如何整合jpa,以及如何使用h2来做单元测试,Swagger接口文档 # 自定义spring-boot-starter之使用注解方式启用 ## 定义启用注解 ```java @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited public @interface EnableExampleService { } ``` ## 自动配置类上加是否存在启用注解 > 关键就是这一句@ConditionalOnBean(annotation = EnableExampleService.class) ```java @Configuration @ConditionalOnBean(annotation = EnableExampleService.class) @ConditionalOnClass(ExampleService.class) @EnableConfigurationProperties(ExampleServiceProperties.class) public class ExampleServiceAutoConfiguration { @Autowired private ExampleServiceProperties exampleServiceProperties; private static final String TEXT_TRANSFORM_LOWERCASE = "lowercase"; private static final String TEXT_TRANSFORM_UPPERCASE = "uppercase"; @Bean @ConditionalOnMissingBean public ExampleService exampleService (){ if(TEXT_TRANSFORM_LOWERCASE.equalsIgnoreCase(exampleServiceProperties.getTextTransform())){ return new ExampleLowercaseServiceImpl(exampleServiceProperties.getPrefix(),exampleServiceProperties.getSuffix()); } if(TEXT_TRANSFORM_UPPERCASE.equalsIgnoreCase(exampleServiceProperties.getTextTransform())){ return new ExampleUppercaseServiceImpl(exampleServiceProperties.getPrefix(),exampleServiceProperties.getSuffix()); } throw new IllegalArgumentException("example.service.text-transform only can be one of lowercase or uppercase"); } } ``` ## resources/META-INF/spring.factories定义好自动化配置类,以便SpringFactoriesLoader加载 ```properties org.springframework.boot.autoconfigure.EnableAutoConfiguration=cn.jaychang.example.ExampleServiceAutoConfiguration ``` # 参考资料 https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#using-boot-maven-without-a-parent https://www.jianshu.com/p/346cac67bfcc https://docs.spring.io/spring-boot/docs/current/reference/html/configuration-metadata.html