【Spring Boot】Starter

Spring Boot Starters帮助我们快速继承并使用各种三方件。

一、命名规范

  • 官方Starter: 遵循spring-boot-starter*格式,如 spring-boot-starter-data-redis、spring-boot-starter-web
  • 非Spring官方: 建议*-spring-boot-starter格式,避免与Spring官方冲突,如nacos-config-spring-boot-starter

二、基本原理

本质是一个Maven项目,作为依赖管理和自动配置的载体。Spring Boot项目中,只需引入相应Starter,就能享受一站式服务,如自动配置和依赖管理

一个Spring Boot Starter主要以下部分组成

  1、依赖管理:在Starter的POM文件中,可以了一系列使用该Starter所必需的依赖,如spring-boot-starter-web中包含了 spring-boot-starter-tomcat,spring-webmvc, spring-web等关于web开发的依赖

  2、自动配置:AutoConfiguratoin

  3、条件注解:@ConditionalXXX

三、自定义Spring Boot Starter

比如创建一个发送邮件的Starter,名为 mail-sender-spring-boot-starter

首先:新建一个Maven项目,并在pom.xml文件定义我们Starter名称和所需的依赖 

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    
    <groupId>com.example</groupId>
    <artifactId>mail-sender-spring-boot-starter</artifactId>
    <version>1.0.0</version>

     <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
    </dependencies>
</project>

然后:我们需要一个自动配置类,定义一个发送邮件的Bean

@Configuration
@ConditionalOnClass(JavaMailSenderImpl.class)
@ConditionalOnProperty(prefix="spring.mail", name="host")
public class MailSenderAutoConfiguration
{
    @Autowired
    private MailProperties mailProperties;

    @Bean
    @ConditionalOnMissingBean
    public JavaMailSender mailSender() {
        JavaMailSenderImpl  mailSender = new JavaMailSenderImpl();
        mailSender.setHost(mailProperties.getHost());
        mailSender.setPort(mailProperties.getPort());
        mailSender.setUserName(mailProperties.getUserName());
        mailSender.setPassword(mailProperties.getPassword());
        return mailSender;
    }
}

在该配置类中 ,

  • @ConditionalOnClass  确保只有JavaMailSenderImpl类存在于类路径中,才进行自动配置;
  • @ConditionalOnProperty  确保只有当spring.mail.host这个配置存在时,才会进行自动配置;
  • @ConditionalOnMissingBean 确保只有当应用中不存在 JavaMailSenderImpl 类型的Bean,才会创建新的Bean

最后:我们需要在 resources/META-INF/spring.factories 文件中指定我们的自动配置类

org.springframewok.boot.autoconfigure.EnableAutoConfiguration=com.example.MailSenderAutoConfiguration

使用:当其他项目POM添加了我们当前Starter依赖,并在配置文件定义 spring.mail.host等属性后,Spring Boot会自动配置并初始化 JavaMailSenderImpl Bean, 开发者就可以直接使用它来发邮件了。

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

 

posted @ 2022-06-05 19:15  飞翔在天  阅读(150)  评论(0编辑  收藏  举报