likes
comments
collection
share

SpringBoot自定义Stater

作者站长头像
站长
· 阅读数 28

SpringBoot starter机制

​ SpringBoot由众多Starter组成(一系列的自动化配置的starter插件),SpringBoot之所以流行,也是因为starter。

starter是SpringBoot非常重要的一部分,可以理解为一个可拔插式的插件,正是这些starter使得使用某个功能的开发者不需要关注各种依赖库的处理,不需要具体的配置信息,由Spring Boot自动通过classpath路径下的类发现需要的Bean,并织入相应的Bean。

例如,你想使用Reids插件,那么可以使用spring-boot-starter-redis;如果想使用MongoDB,可以使用spring-boot-starter-data-mongodb

为什么要自定义starter

开发过程中,经常会有一些独立于业务之外的配置模块。如果我们将这些可独立于业务代码之外的功能配置模块封装成一个个starter,复用的时候只需要将其在pom中引用依赖即可,SpringBoot为我们完成自动装配

自定义starter的命名规则

SpringBoot提供的starter以spring-boot-starter-xxx的方式命名的。官方建议自定义的starter使用xxx-spring-boot-starter命名规则。以区分SpringBoot生态提供的starter

整个过程分为两部分:

  • 自定义starter

  • 使用starter

首先,先完成自定义starter

(1)新建maven jar工程,工程名为custom-spring-boot-starter,导入依赖:


<dependencies>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-autoconfigure</artifactId>

<version>2.2.2.RELEASE</version>

</dependency>

</dependencies>


(2)编写javaBean


@EnableConfigurationProperties(SimpleBean.class)

@ConfigurationProperties(prefix = "simplebean")

public class SimpleBean {

private int id;

private String name;

public int getId() {

return id;

}

public void setId(int 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 + ''' +

'}';

}

}



(3)编写配置类MyAutoConfiguration


@Configuration

@ConditionalOnClass //@ConditionalOnClass:当类路径classpath下有指定的类的情况下进行自动配置

public class MyAutoConfiguration {

static {

System.out.println("MyAutoConfiguration init....");

}

@Bean

public SimpleBean simpleBean(){

return new SimpleBean();

}

}


(4)resources下创建/META-INF/spring.factories

注意:META-INF是自己手动创建的目录,spring.factories也是手动创建的文件,在该文件中配置自己的自动配置类


org.springframework.boot.autoconfigure.EnableAutoConfiguration=

cn.hanyuanhun.config.MyAutoConfiguration


使用自定义starter

(1)导入自定义starter的依赖


<dependency>

<groupId>cn.hanyuanhun</groupId>

<artifactId>custom-spring-boot-starter</artifactId>

<version>1.0-SNAPSHOT</version>

</dependency>


(2)在全局配置文件中配置属性值


simplebean.id=1

simplebean.name=自定义starter


(3)编写测试方法


//测试自定义starter

@Autowired

private SimpleBean simpleBean;

@Test

public void starterTest(){

	System.out.println(simpleBean);

}


原文链接 www.hanyuanhun.cn | node.hanyuanhun.cn

转载自:https://juejin.cn/post/7382757732670242854
评论
请登录