自定义实现SpringBoot Starter

发布时间 2023-04-26 11:04:38作者: 浪迹天涯的派大星

在日常的开发中,会将开发的公共jar包发布的仓库,这样可以实现代码的复用。这里介绍的是自定义SpringBoot Starter的方式,对于采用SpringBoot开发的项目来说,引入和使用非常的方便。

1、SpringBoot Starter介绍

SpringBoot和Spring相比,在配置上简化了很多,核心就是因为Starter引入了一些需要的依赖和初始化的配置,从而实现开箱即用的效果。Starter其实干了两件事,一件是起步依赖,一件是自动装配,前者让将我们需要的依赖整合到一起,后者将我们需要的Bean自动的注入到了Spring容器。Starter的自动装配需要其实是扫描jar下的MATE-INF/spring.factories文件中的配置。

2、依赖引入

引入spring-boot-starter依赖,里面已经包含了spring-boot-autoconfigure依赖,然后引入一下自己开发需要的依赖。

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

3、开发实现

自行实现逻辑,一般采用构造器注入的方式,如下简单例子,HelloService采用构造器的方式注入依赖的HelloWorld:

public class HelloWorld {
    public void sayHelloWorld() {
        System.out.println("hello world");
    }
}
public class HelloService {

    private HelloWorld helloWorld;

    public HelloService() {

    }

    public HelloService(HelloWorld helloWorld) {
        this.helloWorld = helloWorld;
    }

    public void sayHello() {
        helloWorld.sayHelloWorld();
    }
}

4、编写配置类

新建一个autoconfig文件夹,然后新建一个配置类,搭配@Configuration和@Bean注入实例,然后搭配@Condition控制Bean的注入条件,如下:

@ConditionalOnProperty(prefix = "demo", name = "say", havingValue = "hello")
@Configuration
public class DemoConfig {

    @Bean
    public HelloWorld helloWorld() {
        return new HelloWorld();
    }

    @Bean
    public HelloService helloService() {
        System.out.println("helloService bean success");
        return new HelloService(helloWorld());
    }
}

5、@Condition系列注解

org.springframework.boot.autoconfigure.condition包路径下,存在如下很多注解,大部分注解都是见名知意,例如:

@ConditionalOnBean表示当前上下文存在指定Bean时,才实例化Bean

@ConditionalOnClass表示classPath存在指定类时,才实例化Bean,其他不再赘述,可以查看注解上的注释。

6、创建spring.factories文件

spring.factories中的配置如下,指定@Configuration所在的配置类:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=org.example.autoconfig.DemoConfig

7、打包发布

可以发布到本地Maven仓库给其他项目引用,也可以发布到公司私服,给其他人引用,或者将打包的jar给出去,采用引入本地jar的方式使用。