手写一个springboot starter

springboot的starter的作用就是自动装配。将配置类自动装配好放入ioc容器里。作为一个组件,提供给springboot的程序使用。

今天手写一个starter。功能很简单,调用starter内对象的一个方法输出"hello! xxx"

先来了解以下命名规范

  • 自定义 starter,工程命名格式为{xxx}-spring-boot-starter

  • 官方starter,工程命名格式为spring-boot-starter-{xxx}

1.新建一个普通的maven工程,引入springboot依赖(2.5.6),项目名为hello-spring-boot-starter

pom.xml

<dependencies>
<!--很关键-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
<version>2.5.6</version>
</dependency>
<!--springBoot-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>2.5.6</version>
</dependency>
<!-- Lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
</dependencies>
<!--打pom包的插件-->
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.0</version>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>

 2.编写业务类HelloStarter 

@Data                   //生成getset
@AllArgsConstructor     //生成有参构造器
public class HelloStarter {
    //业务类依赖的一些配置信息,通过spring.properties配置
    private HelloProperties helloProperties;

    public String hello() {
        return "hello! " + helloProperties.name;
    }
}

 3.编写配置信息类

@ConfigurationProperties(prefix = "com.shuai.hello")  //绑定到spring.properties文件中
@Data
public class HelloProperties {
    String name;
}

4. 编写自动配置类,将所有对象注入到容器中。

@Configuration      //表明这是一个springBoot的配置类
public class AutoConfiguration {

    @Bean           //将对象放入IOC容器中,对象名就是方法名
    public HelloProperties helloProperties(){
        return new HelloProperties();
    }
    @Bean           //将对象放入IOC容器中,对象名就是方法名
    public HelloStarter helloStarter(@Autowired HelloProperties helloProperties){ //自动注入
        return new HelloStarter(helloProperties);
    }
}

5.为了让springboot容器扫描到配置类,建一个resource目录,一个META-INF文件夹和spring.factories文件

 在spring.factories文件中写入

#等号后面是配置类的全路径
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.config.AutoConfiguration

6.使用install打包到本地仓库

注意:

所以一般我们使用install打包

 7.导入项目中进行测试
       <dependency>
            <groupId>com.shuai</groupId>
            <artifactId>hello-spring-boot-starter</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
使用starter中的对象
@RestController
public class HelloController {
    @Autowired
    HelloStarter helloStarter;
    @RequestMapping("/hello")
    public String hello(){

        return helloStarter.hello();
    }
}
spring.properties中配置信息
com.shuai.hello.name="starter"

访问http://localhost:8080/hello 测试结果

 

非常棒!你现在已经会写一个简单的starter了,但是这远远不够,后续还要加上@EnableConfigurationProperties,@EnableConfigurationProperties等注解,让你的starter更加健壮

 

寄语:我们所要追求的,永远不是绝对的正确,而是比过去的自己更好。

posted @ 2021-12-15 17:18  小猴子_X  阅读(972)  评论(0编辑  收藏  举报