0
点赞
收藏
分享

微信扫一扫

手写springboot starter

转载自:www.javaman.cn

一、创建自己的springboot-starter

好的,下面是手写一个自己的Spring Boot Starter自动装配的流程和代码:

1、创建一个Maven项目,命名为my-spring-boot-starter

2、在pom.xml文件中添加以下依赖:

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter</artifactId>
     <version>2.5.5</version>
 </dependency>

3、创建一个自动配置类MyAutoConfiguration,该类需要添加@Configuration和@EnableConfigurationProperties注解,其中@EnableConfigurationProperties注解用于启用自定义配置属性类。

@Configuration
 @EnableConfigurationProperties(MyProperties.class)
 public class MyAutoConfiguration {
     private final MyProperties properties;
 
     public MyAutoConfiguration(MyProperties properties) {
         this.properties = properties;
     }
 
     @Bean
     public MyService myService() {
         return new MyService(properties.getMessage());
     }
 }

4、创建一个自定义配置属性类MyProperties,该类需要添加@ConfigurationProperties注解,并指定属性的前缀。

@ConfigurationProperties(prefix = "my")
 public class MyProperties {
     private String message = "Hello World";
 
     public String getMessage() {
         return message;
     }
 
     public void setMessage(String message) {
         this.message = message;
     }
 }

5、创建一个自定义服务类MyService,该类需要添加@Component注解。

@Component
 public class MyService {
     private final String message;
 
     public MyService(String message) {
         this.message = message;
     }
 
     public String getMessage() {
         return message;
     }
 }

6、创建一个自定义starter类MyStarter,该类需要添加@Configuration注解,并指定自动配置类MyAutoConfiguration。

@Configuration
 @Import(MyAutoConfiguration.class)
 public class MyStarter {
 }

7、在resources/META-INF目录下创建spring.factories文件,该文件需要添加以下内容:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
 com.example.demo.MyStarter

8、打包my-spring-boot-starter项目,并将其安装到本地Maven仓库中。

二、其他Spring Boot项目使用

1、在其他Spring Boot项目中添加以下依赖:

<dependency>
     <groupId>com.example</groupId>
     <artifactId>my-spring-boot-starter</artifactId>
     <version>1.0.0</version>
 </dependency>

2、在其他Spring Boot项目中使用自定义服务类MyService。

@RestController
 public class MyController {
     private final MyService myService;
 
     public MyController(MyService myService) {
         this.myService = myService;
     }
 
     @GetMapping("/message")
     public String getMessage() {
         return myService.getMessage();
     }
 }

以上就是手写一个自己的Spring Boot Starter自动装配的流程和代码。简单来说,就是创建一个自动配置类,将自定义服务类和自定义配置属性类注入到自动配置类中,然后创建一个自定义starter类,并在spring.factories文件中指定该自定义starter类,最后在其他Spring Boot项目中添加依赖并使用自定义服务类即可。

举报

相关推荐

0 条评论