目录
1 简介
2 规范
2.1 命名
2.2 模块划分
3 示例
SpringBoot中的starter是一种非常重要的机制,能够抛弃以前繁琐的配置,将其统一集成进starter,应用者只需要在maven中引入starter依赖,SpringBoot就自动扫描到要加载的信息并启动相应的默认配置,starter让我们摆脱了各种依赖库的处理,SpringBoot会自动通过classpath路径下的类发现需要的bean,并注册进IOC容器,SpringBoot提供了针对日常企业研发应用研发各种场景的spring-boot-starter依赖模块。
SpringBoot提供的starter以spring-boot-starter-xxx的方式命名,如mvc
org.springframework.boot spring-boot-starter-web
而第三方默认自定义的starter使用xxx-spring-boot-starter的命名规则,以此来区分springBoot提供的starter,如mybatis。这也是约定大于配置的一种理念。
com.baomidou mybatis-plus-boot-starter 3.4.0
一个标准Spring boot Starter的组成:
autoconfigure模块:一般包含自动配置相关代码
starter模块:提供对autoconfigure模块的依赖以及其他的二方依赖,一般业务方通过依赖starter来实现这个组件的依赖
功能:分每一个分配中国国籍
相关依赖:
4.0.0 org.springframework.boot spring-boot-starter-parent 2.2.6.RELEASE com.liubujun learn-spring-boot-starter 0.0.1-SNAPSHOT learn-spring-boot-starter Demo project for Spring Boot 1.8 org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-configuration-processor org.springframework.boot spring-boot-autoconfigure org.projectlombok lombok
第一个工程结构如下:

准备一个Service:
public interface UserService {String printUser(String name);
}
Service的实现类:
@Service
public class UserServiceImpl implements UserService {LearnProperties learnProperties;public UserServiceImpl(LearnProperties learnProperties) {this.learnProperties = learnProperties;}@Overridepublic String printUser(String name) {return name+" is a citizen of "+learnProperties.getNationality();}
}
属性类:国籍从application.properties文件中获取
@ConfigurationProperties(prefix = "starter.user") //将配置文件中的相关属性与Java Bean进行动态绑定
@Data
public class LearnProperties {/*** 国籍*/private String nationality;}
配置类:
@Configuration
@EnableConfigurationProperties(LearnProperties.class) //让使用@ConfigurationProperties注解的类(LearnProper)生效
@ConditionalOnProperty(prefix = "starter",name = "isopen",havingValue = "true",matchIfMissing = true)
public class StarterAutoConfig {@AutowiredLearnProperties learnProperties;@BeanUserService userService(){return new UserServiceImpl(learnProperties);}
}
//prefix为配置文件中的前缀,
//name为配置的名字
//havingValue是与配置的值对比值,当两个值相同返回true,配置类生效
添加文件工厂:spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\com.liubujun.learnspringbootstarter.config.StarterAutoConfig
以上是第一个工程配置完成之后进行打包:

如此一个starter就制作完成了,那么如何使用它呢,可以想一想平时我们使用第三方依赖的时候是如何去使用它们的starter的,只需要在pom文件中引入该starter就好了。
此时准备第二个工程进行测试,工程结构如下:

步骤一:
在pom文件中引入上一个工程的依赖,如下:
com.liubujun learn-spring-boot-starter 0.0.1-SNAPSHOT
步骤二:
在配置文件中进行配置(此处的配置是根据引入上一个工程的依赖来进行配置的,就是第一个工程的属性类)
starter.user.nationality=the People's Republic of China
starter.isopen=true
步骤三:
建一个测试类
@RestController
@RequestMapping("test")
public class TestController {@ResourceUserService userService;@GetMapping("test")public String testController(String name){return userService.printUser(name);}
}
测试结果如下:

可以发现,引入了另外一个工程的starter之后,可以使用里面的相关代码,这也侧面印证了自己之前只引入依赖而没有思考是如何实现的。
上一篇:消息发布确认