创建SpringBoot Starter教程附源码
源码:https://gitee.com/learning_demo/starter-demo
一、介绍
- 本项目中主要以读取配置文件内容为例,介绍如何创建Starter的jar包。
二、注意事项
- 工程要使用maven的compile插件,不能使用spring-boot-maven-plugin插件,不然install得到的jar是一个可运行的jar,无法被其它工程使用;检查方法:看jar包中class是否直接在根目录。
三、操作步骤
-
1.按平常一样编写相应类,类统一在@Configuration注解类下注入到IOC容器中。
-
2.在resources/META-INF/下创建spring.factories文件,并将@Configuration注解类添加在=号后面,多个使用逗号隔开:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.example.config.AutoConfigBean -
3.使用mvn install 将jar包安装到maven仓库(同时会在target中生成)
-
4.测试:在另外工程添加依赖,创建一个单元测试对DemoService中的方法进行测试
<dependency>
<groupId>com.example</groupId>
<artifactId>demo-spring-boot-starter</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
@Test
void testDemo(){
demoService.printDemoProperties();
}
四、高能操作
-
正常是通过 @Configuration的方式将bean管理起来的,再将这个文件配置到spring.factories中,工程启动时就会自动加载到容器中
-
直接在类上使用注解@Component,然后在启动类上加上扫描包,已验证,是可以的。但也有不足,需要使用方指定扫描
@SpringBootApplication
@ComponentScan(basePackages = {"org.test1","org.test2"}) -
新方案:
在@Configuration类上加上@ComponentScan,就可以实现:
1、自定义扫描路径下边带有@Controller,@Service,@Repository,@Component注解加入spring容器
2、通过includeFilters加入扫描路径下没有以上注解的类加入spring容器
3、通过excludeFilters过滤出不用加入spring容器的类
4、自定义增加了@Component注解的注解方式
本文来自博客园,作者:咔咔皮卡丘,转载请注明原文链接:https://www.cnblogs.com/anquing/p/14842259.html