手写一个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




org.springframework.boot
spring-boot-configuration-processor
true
2.5.6



org.springframework.boot
spring-boot-autoconfigure
2.5.6



org.projectlombok
lombok
1.18.20






org.apache.maven.plugins
maven-compiler-plugin
3.6.0

8
8



 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.导入项目中进行测试
       
            com.shuai
            hello-spring-boot-starter
            1.0-SNAPSHOT
        
使用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更加健壮

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