SpringBoot starter机制
SpringBoot中的starter是一种非常重要的机制,能够抛弃以前繁杂的配置,将其统一集成进starter,应用者只需要在Maven中引入starter依赖,SpringBoot就能自动扫描到要加载的信息并启动相应的默认配置,starter让我们摆脱了各种依赖库的处理,需要配置各种信息的困扰。SpringBoot会自动通过classpath路径下的类发现需要的Bean,并注册进IOC容器,SpringBoot提供了针对日常企业应用研发各种场景的spring-boot-starter依赖模块,所有这些模块都遵循着约定大于配置的理念。简而言之,starter就是一个外部的项目,我们需要使用它的时候就可以在当前SpringBoot项目中引入它。
为什么要自定义starter
在我们的日常开发工作中,经常会有一些独立于业务之外的配置模块,我们经常将其放到一个特定的包下,然后如果另一个工程需要复用这块功能的时候,需要将代码硬拷贝到另一个工程,重新集成一遍,麻烦至极,如果我们将这些可独立于业务代码之外的功能配置模块封装成一个个starter,复用的时候只需要将其在pom中引入依赖即可,再由SpringBoot为我们完成自动装配。就非常轻松了。
自定义starter的命名规则
SpringBoot提供的starter以spring-boot-starter-xxx的方式命名的
官方建议自定义的starter使用xxx-spring-boot-starter命名规则,以区分SpringBoot生态提供的starter
自定义starter代码实现:
一、自定义starter
第一步:创建一个普通的Maven工程并导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>2.2.9.RELEASE</version>
</dependency>
第二步:编写一个通用的pojo类
package com.gy.pojo;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
@EnableConfigurationProperties
@ConfigurationProperties(prefix = "simplebean")
public class SimpleBean {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "SimpleBean{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
第三步:编写一个表示加载依赖的配置文件
package com.gy.config;
import com.gy.pojo.SimpleBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyConfiguration {
static {
System.out.println("MyConfiguration init....");
}
@Bean
public SimpleBean simpleBean(){
return new SimpleBean();
}
}
第四步:在resources下创建MATE-INF/spring.factories文件并配置
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.gy.config.MyConfiguration
二、使用自定义的starter
第一步:在一个SpringBoot项目中引入自定义starter坐标
<dependency>
<groupId>com.gy</groupId>
<artifactId>gy-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
第二步:给simpleBean赋值
simplebean.id=1
simplebean.name=高楊
第三步:测试即可
package springbootmytest;
import com.gy.pojo.SimpleBean;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SpringbootMytestApplicationTests {
@Autowired
private SimpleBean simpleBean;
@Test
void contextLoads() {
System.out.println(simpleBean);
}
}