自定义-starter
2021/8/25 23:08:24
本文主要是介绍自定义-starter,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
目录- 说明
- 编写启动器
- 新建项目测试我们自己写的启动器
分析完毕了源码以及自动装配的过程,可以尝试自定义一个启动器来玩玩!
自动装配的过程
SpringBoot-静态资源加载-源码
SpringBoot-Web-初见
说明
启动器模块是一个 空 jar 文件,仅提供辅助性依赖管理,这些依赖可能用于自动装配或者其他类库;
命名归约:
官方命名:
- 前缀:spring-boot-starter-xxx
- 比如:spring-boot-starter-web....
自定义命名:
- xxx-spring-boot-starter
- 比如:mybatis-spring-boot-starter
编写启动器
1、在我们的 starter 中 导入 autoconfigure 的依赖!
<!-- 启动器 --> <dependencies> <!-- 引入自动配置模块 --> <dependency> <groupId>com.kuang</groupId> <artifactId>kuang-spring-boot-starter-autoconfigure</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> </dependencies>
2、将 autoconfigure 项目下多余的文件都删掉,Pom中只留下一个 starter,这是所有的启动器基本配置!
3、我们编写一个自己的服务
public class HelloService { HelloProperties helloProperties; public HelloProperties getHelloProperties() { return helloProperties; } public void setHelloProperties(HelloProperties helloProperties) { this.helloProperties = helloProperties; } public String sayHello(String name){ return helloProperties.getPrefix() + name + helloProperties.getSuffix(); } }
4、编写HelloProperties 配置类
// 前缀 zwt.hello @ConfigurationProperties(prefix = "zwt.hello") public class HelloProperties { private String prefix; private String suffix; public String getPrefix() { return prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getSuffix() { return suffix; } public void setSuffix(String suffix) { this.suffix = suffix; } }
5、编写我们的自动配置类并注入bean,测试!
@Configuration @ConditionalOnWebApplication //web应用生效 @EnableConfigurationProperties(HelloProperties.class) public class HelloServiceAutoConfiguration { @Autowired HelloProperties helloProperties; @Bean public HelloService helloService(){ HelloService service = new HelloService(); service.setHelloProperties(helloProperties); return service; } }
6、在resources编写一个自己的 META-INF\spring.factories
# Auto Configure org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.zwt.HelloServiceAutoConfiguration
7、编写完成后,可以安装到maven仓库中! (install)
新建项目测试我们自己写的启动器
1、新建一个SpringBoot 项目
2、导入我们自己写的启动器
<dependency> <groupId>com.zwt</groupId> <artifactId>kuang-spring-boot-starter</artifactId> <version>1.0-SNAPSHOT</version> </dependency>
3、编写一个 HelloController 进行测试我们自己的写的接口!
@RestController public class HelloController { @Autowired HelloService helloService; @RequestMapping("/hello") public String hello(){ return helloService.sayHello("zxc"); } }
4、编写配置文件 application.properties
zwt.hello.prefix="ppp" zwt.hello.suffix="sss"
这篇关于自定义-starter的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-05小米13T Pro系统合集:性能与摄影的极致融合,值得你升级的系统ROM
- 2024-10-01基于Python+Vue开发的医院门诊预约挂号系统
- 2024-10-01基于Python+Vue开发的旅游景区管理系统
- 2024-10-01RestfulAPI入门指南:打造简单易懂的API接口
- 2024-10-01初学者指南:了解和使用Server Action
- 2024-10-01Server Component入门指南:搭建与配置详解
- 2024-10-01React 中使用 useRequest 实现数据请求
- 2024-10-01使用 golang 将ETH账户的资产平均分散到其他账户
- 2024-10-01JWT用户校验课程:从入门到实践
- 2024-10-01Server Component课程入门指南