关于springboot:Spring-Boot如何自定义Spring-Boot-Starter

4次阅读

共计 4780 个字符,预计需要花费 12 分钟才能阅读完成。

本文介绍

咱们都晓得 Spring Boot 我的项目由一个个的 starter 形成,比方 web 的 starter,redis 的 starter 等等。
咱们通过 maven 引入对应的 starter,简直毋庸配置就能够完满应用集成的 spring mvc 或 redis.

那么咱们如何自定义一个 starter 呢?

本文用将示如何应用 SpringBoot 的 Auto-Configuration 个性创立本人的Spring Boot Starter

假如 Toy 为咱们须要集成为 starter 框架或者类,并且心愿在利用启动的时候就加载到 Spring 上下文中供咱们调用。

有的小伙伴可能会问为什么要这样做?间接将 Toy 申明为 Spring 的 bean 不就好了。

答案必定是能够这样做,不过秉承 Spring Boot 疾速上手的准则,通过引入 starter 的形式能够更加疾速应用集成的咱们想要的性能或者个性,就好比下面的Toy

又比方 mybatis,因为咱们无奈批改 mybatis 源码,路径之一是通过 @Bean 的形式在办法上创立SqlSessionFactory bean,并在 Spring Boot 利用中应用。

路径二则是通过创立 starter,须要用到 mybatis 的中央引入 mybatis 的 starter 就可实现 mybatis 的集成。

在很多我的项目须要集成 mybatis 的状况下,starter 的形式会更为疾速高效。

我的项目构造

本我的项目分为两个模块:

toy-sample-apptoy-spring-boot-starter

  • toy-sample-app: 演示如何引入本人创立的 starter
  • toy-spring-boot-starter: starter 模块,用于构建Toy Spring Bean 供演示我的项目应用

代码介绍

toy-spring-boot-starter

  • META-INF/spring.factories 文件

该文件指明了主动注入的的类名,Spring Boot 利用启动的时候会将该类初始化并加载到上下文中。

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
        cn.bugkit.toy.autoconfigure.ToyAutoConfiguration
  • ToyAutoConfiguration 文件

@Configuration 注解阐明是 Spring 的配置类

@EnableConfigurationProperties(ToyProperties.class)注解指定了须要应用的属性配置类

package cn.bugkit.toy.autoconfigure;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author bugkit
 * @since 2022.2.24
 */
@Configuration
@EnableConfigurationProperties(ToyProperties.class)
public class ToyAutoConfiguration {

    @Autowired
    private ToyProperties toyProperties;

    @Bean
    public Toy toy(){return new Toy(toyProperties.getName(),toyProperties.getPassword(), toyProperties.getWeight());
    }

}
  • ToyProperties 文件

该类申明了须要从 application.properties 文件读取的属性,供上述文件的 toy() 办法构建所须要的 Toy 对象。

/**
 * @author bugkit
 * @since 2022.2.24
 */
@Configuration
@ConfigurationProperties(prefix = "toy")
public class ToyProperties {
    private String name;
    private String password;
    private int weight;

    public String getName() {return name;}

    public void setName(String name) {this.name = name;}

    public String getPassword() {return password;}

    public void setPassword(String password) {this.password = password;}

    public int getWeight() {return weight;}

    public void setWeight(int weight) {this.weight = weight;}
}
  • Toy 文件

提供了咱们须要的 showInfo() 办法,具体在 toy-sample-app 我的项目中用到

public class Toy {
    private String name;
    private String password;
    private int weight;

    public Toy(String name, String password, int weight) {
        this.name = name;
        this.password = password;
        this.weight = weight;
    }

    public String getName() {return name;}

    public void setName(String name) {this.name = name;}

    public String getPassword() {return password;}

    public void setPassword(String password) {this.password = password;}

    public int getWeight() {return weight;}

    public void setWeight(int weight) {this.weight = weight;}

    public void showInfo(){System.out.println("===================start==========================");
        System.out.println("Toy [ Name:" + name +", password:" + password +", weight:" + weight + "]");
        System.out.println("===================end============================");
    }
}

toy-sample-app 我的项目

该我的项目用于演示如何应用咱们本人构建的 toy-spring-boot-starter

  • pom 文件

pom 文件引入 starter 我的项目的 jar

 <dependency>
    <groupId>cn.bugkit</groupId>
    <artifactId>toy-spring-boot-starter</artifactId>
    <version>0.0.1-SNAPSHOT</version>
</dependency>
  • ToyService 文件

该类注入 starter 我的项目的 Toy bean,并在 ToyService 初始化实现后调用ToyshowInfo()办法

package cn.bugkit.toy.app.service;

import cn.bugkit.toy.autoconfigure.Toy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

/**
 * @author bugkit
 * @since 2022.2.24
 */
@Service
public class ToyService {

    @Autowired
    private Toy toy;

    @PostConstruct
    public void init() {toy.showInfo();
    }

}
  • application.properties 文件

该文件的 key(如 toy.name) 对应 starter 我的项目的 ToyProperties 类。

toy.name=Hello Kitty
toy.password=kitty@1234
toy.weight=99
  • 控制台启动日志

    .   ____          _            __ _ _
     /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
    (()\___ | '_ |'_| | '_ \/ _` | \ \ \ \
     \\/  ___)| |_)| | | | | || (_| |) ) ) )
    '  |____| .__|_| |_|_| |_\__, | / / / /
     =========|_|==============|___/=/_/_/_/
     :: Spring Boot ::                (v2.6.3)
    
    2022-02-24 14:53:24.092  INFO 14652 --- [main] c.bugkit.toy.app.StarterDemoApplication  : Starting StarterDemoApplication using Java 1.8.0_211 on Bennetty74 with PID 14652 (E:\ideaProjects\spring-learning\toy-sample-app\target\classes started by Bennetty74 in E:\ideaProjects\spring-learning)
    2022-02-24 14:53:24.092  INFO 14652 --- [main] c.bugkit.toy.app.StarterDemoApplication  : No active profile set, falling back to default profiles: default
    ===================start==========================
    Toy [Name: Hello Kitty, password: kitty@1234, weight: 99]
    ===================end============================
    2022-02-24 14:53:24.608  INFO 14652 --- [main] c.bugkit.toy.app.StarterDemoApplication  : Started StarterDemoApplication in 0.888 seconds (JVM running for 1.836)
    
    Process finished with exit code 0

总结

  • toy-spring-boot-starter:咱们通过 Spring Boot 的 Auto-Configuration 个性集成Toy
  • toy-sample-app:在须要用到的 starter 的中央引入 starter 的 maven 依赖,从而能够应用 Toy 对应的 Spring Bean

可选

残余代码能够查看 Github 仓库源码,这里不再赘述。

代码地址:https://github.com/bennetty74…

正文完
 0