springboot原理应用-手写starter

springboot starter组件

spring官方组件和第三方组件有一些差别,主要体现在:

  • 通过组件命名方式表明当前组件的提供者
    spring官方组件命名 spring-boot-starter-XXX ,比如spring-boot-starter-web
    第三方组件命名: XXX-spring-boot-starter, 比如mybatis-spring-boot-starter
  • 自动配置类的加载方式
    spring官方组件一般是通过条件方式控制Bean的装载
    非官方组件,是通过扫描spring.fatories文件中配置的自动装配类,由ImportSelector机制去扫描自动装配类完成Bean的装载
    starter组件相当于一个模块,它整合了当前模块所需要依赖的jar包,并且完成当前模块所需要的Bean的自动装配

1.创建项目

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

2. 创建starter组件

这里模拟手写一个redis的starter, 需要再创建一个项目:
在这里插入图片描述
在这里插入图片描述
创建好之后,添加springboot 和Redisson的依赖

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter</artifactId>
      <version>2.3.1.RELEASE</version>
      <!-- 禁止传递依赖 -->
      <optional>true</optional>
    </dependency>
 <dependency>
      <groupId>org.redisson</groupId>
      <artifactId>redisson</artifactId>
      <version>3.13.1</version>
    </dependency>

然后创建一个自动配置类RedissonAutoConfiguration,自动装在RedissonClient 这个bean:
在这里插入图片描述

package com.lchtest.redission;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@ConditionalOnClass(Redisson.class)  // 条件装配,classpath中存在Redisson 类才装在
@EnableConfigurationProperties(RedissionProperties.class)
@Configuration
public class RedissonAutoConfiguration {

    // 通过RedissonClient去操作redis, 这里需要装配这个Bean到IOC容器中   RedissionProperties是依赖注入
    @Bean
    RedissonClient redissonClient(RedissionProperties redissionProperties){
        Config config = new Config();
        String prefix = "redis://";
        if(redissionProperties.isSsl()){
            prefix = "rediss://";  // 加密请求
        }
        SingleServerConfig singleServerConfig = config.useSingleServer()
                .setAddress(prefix + redissionProperties.getHost() + ":" + redissionProperties.getPort())
                .setConnectTimeout(redissionProperties.getTimeout());
        return Redisson.create(config);
    }
}

创建一个配置读取类RedissionProperties

package com.lchtest.redission;

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "test.redisson")
public class RedissionProperties {
    private String host = "localhost";
    private int port = 6379;
    private int timeout =5000;
    private boolean ssl ;
// getter setter 略
}

META-INF/spring.factories 中配置:org.springframework.boot.autoconfigure.EnableAutoConfiguration=
com.lchtest.redission.RedissonAutoConfiguration
在这里插入图片描述
然后打包安装到本地maven仓,删掉_remote.repositories 文件

3.使用starter组件

本地启动redis(参考 下载并安装windows版本的Redis)
在第一步创建的项目中使用starter组件,pom中加入starter组件依赖:

  <dependency>
            <groupId>com.lchtest.redission</groupId>
            <artifactId>redission-spring-boot-starter</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

然后创建一个controller,这时使用Autowired注解注入RedissonClient 就不会报错了,

package com.lchtest.example.springbootdemo02;

import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @Autowired
    private RedissonClient redissonClient;

    @GetMapping("/say")
    public String say() {
        RBucket<Object> bucket = redissonClient.getBucket("name");
        if (bucket.get() == null) {
            bucket.set("test RedissonClient");
        }
        return bucket.get().toString();
    }
}

配置文件中 添加redis server的host配置:

test.redisson.host=127.0.0.1

然后访问:
在这里插入图片描述
redis客户端中可以看到这个值是被序列化过了的:
在这里插入图片描述

3.starter组件配置项的自动提示

在上面配置文件中,是没有配置项的提示的,我们还需要在starter组件中做一些事情来实现配置项名称的提示;在redission-spring-boot-starter 这个工程的pom文件中,加入spring-boot-configuration-processor的依赖:

  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-configuration-processor</artifactId>
      <version>2.3.1.RELEASE</version>
      <optional>true</optional>
    </dependency>

然后在META-INF目录下创建一个additional-spring-configuration-metadata.json 文件,文件名只能是这个,文件内容如下:
在这里插入图片描述
然后clean install , 安装到本地maven仓
在spring-boot-demo02 项目中更新maven依赖,这时配置属性时就有提示了:
在这里插入图片描述

当然可以!以下是一个简单的示例,展示了如何手写一个Spring Boot Starter: 首先,创建一个 Maven 项目,并添加以下依赖项: ```xml <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <version>2.5.4</version> </dependency> </dependencies> ``` 接下来,创建一个自定义的自动配置类,用于配置你的 Starter: ```java @Configuration @EnableConfigurationProperties(MyStarterProperties.class) public class MyStarterAutoConfiguration { private final MyStarterProperties properties; public MyStarterAutoConfiguration(MyStarterProperties properties) { this.properties = properties; } // 在此处定义你的自动配置逻辑 @Bean public MyStarterService myStarterService() { return new MyStarterService(properties); } } ``` 然后,创建一个属性类,用于将外部配置绑定到属性上: ```java @ConfigurationProperties("my.starter") public class MyStarterProperties { private String message; // 提供 getter 和 setter } ``` 最后,创建一个自定义的服务类,该服务类将在你的 Starter 中使用: ```java public class MyStarterService { private final MyStarterProperties properties; public MyStarterService(MyStarterProperties properties) { this.properties = properties; } public void showMessage() { System.out.println(properties.getMessage()); } } ``` 现在,你的 Spring Boot Starter 已经准备就绪了!你可以将其打包并使用在其他 Spring Boot 项目中。在其他项目的 `pom.xml` 文件中,添加你的 Starter 依赖: ```xml <dependencies> <dependency> <groupId>com.example</groupId> <artifactId>my-starter</artifactId> <version>1.0.0</version> </dependency> </dependencies> ``` 然后,在你的应用程序中使用 `MyStarterService`: ```java @SpringBootApplication public class MyApplication implements CommandLineRunner { private final MyStarterService myStarterService; public MyApplication(MyStarterService myStarterService) { this.myStarterService = myStarterService; } public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } @Override public void run(String... args) throws Exception { myStarterService.showMessage(); } } ``` 这样,你就成功地创建了一个简单的 Spring Boot Starter!当其他项目引入你的 Starter 并运行时,将会输出预定义的消息。 当然,这只是一个简单的示例,真实的 Starter 可能包含更多的配置和功能。你可以根据自己的需求进行扩展和定制。希望对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值