自定义starter

pom.xml

创建一个新的springboot工程pom文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.ww</groupId>
    <artifactId>myfirst-spring-boot-starter</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

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

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

    </dependencies>
</project>

ControllerProperties属性类

ConfigurationProperties注解可以在配置文件中配置了,前缀就是mycp

@ConfigurationProperties(prefix = "mycp")
public class ControllerProperties {
    @Value("hello")
    private String msg;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}

StarterAutoConfiguration自动装配类

@Configuration
@EnableConfigurationProperties(ControllerProperties.class)
public class StarterAutoConfiguration {

    @Bean
    public StarterController starterController(ControllerProperties controllerProperties) {
        return new StarterController(controllerProperties.getMsg());
    }
}

StarterController控制器,测试用

public class StarterController {

    private String msg;

    public StarterController(String msg){
        this.msg=msg;
    }

    public void hello() {
        System.out.println(msg);
    }
}

添加spring.factories

[图片上传中...(image-d6c6b7-1684848509801-7)]

内容为自动装配类全限定名。

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.ww.starter.StarterAutoConfiguration

安装到本地仓库

可以用maven的命令mvn clean install

image.png

测试

在其他项目中引入:

 <dependency>
            <groupId>com.ww</groupId>
            <artifactId>myfirst-spring-boot-starter</artifactId>
            <version>0.0.1-SNAPSHOT</version>
 </dependency>

运行:


image.png

输出了默认值:


image.png

我们在配置文件修改试试:


image.png
image.png

至此我们自定义了一个starter,其实步骤也很简单,定义自动配置类,创建spring.factories并配置进去,创建属性配置类,添加相应的注解,打包发布,其他项目可以引用。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容