Springboot自定义Stater

1、默认启动器
Boot会将项目中常用的场景做成对应的starter启动器,项目中涉及到什么场景就引入该场景对应的启动器,项目中引入这些启动器之后,和这个starter相关的依赖也会被引入。比如引入测试和基本的启动器

再如这里引入web开发的启动器

其他stater查看官方文档

2、自定义启动器
如上,boot已经提供了好多常用的starter场景,即使这样有时候我们需要将自己一个公用的业务模块抽成一个starter,需要用到的地方直接使用starter即可,比如分析

分析官网starter定义方式,如引入测试starter

org.springframework.boot spring-boot-starter-test test 分析可以看出如下,starter没有任何实现,只是依赖管理,底层的依赖是一个自动配置类和其他依赖

底层依赖有个spring-boot-test-autoconfigure依赖用于和boot配置

按照上面的模式,定义一个starter步骤如下

启动器(starter)是一个空的jar文件,仅仅提供辅助性依赖管理,这些依赖可能用于自动装配或其他类库。
需要专门写一个类似spring-boot-autoconfigure的配置模块
用的时候只需要引入启动器starter,就可以使用自动配置了
SpringBoot提供的starter以spring-boot-starter-xxx的方式命名的。官方建议自定义的starter使用xxx-spring-boot-starter命名规则。以区分SpringBoot生态提供的starter。

我们定义hello-spring-boot-starter,创建一个starter,是一个空的jar项目

再创建一个自动配置项目hello-spring-boot-starter-autoconfig

依赖

4.0.0 org.springframework.boot spring-boot-starter-parent 2.5.1 com.example hello-spring-boot-starter-autoconfig 0.0.1-SNAPSHOT hello-spring-boot-starter-autoconfig Demo project for Spring Boot 自动配置类

@Configuration
@ConditionalOnMissingBean({Hello.class})
@EnableConfigurationProperties({HelloProperties.class})
public class HelloAutoConfiguration {
@Bean
public Hello hello() {
Hello hello = new Hello();
return hello;
}
}
和自动配置类绑定的配置文件类

@ConfigurationProperties(“hello”)
public class HelloProperties {
private String pre;
private String end;

public String getPre() {
    return pre;
}

public void setPre(String pre) {
    this.pre = pre;
}

public String getEnd() {
    return end;
}

public void setEnd(String end) {
    this.end = end;
}

}
主业务类

public class Hello {

@Autowired
HelloProperties helloProperties;

public String sysHello(String userName){
    return helloProperties.getPre()+userName+helloProperties.getEnd();
}

}
spring.factories

org.springframework.boot.autoconfigure.EnableAutoConfiguration=
com.example.auto.HelloAutoConfiguration
最后将这两个项目install,然后再其他工程引入starter即可

org.example
hello-spring-boot-starter
1.0-SNAPSHOT

且可以配置文件中配置

hello.pre=zhangsan
hello.end=你好

文章转自:Springboot自定义Stater_Java-答学网

作者:答学网,转载请注明原文链接:http://www.dxzl8.com/

猜你喜欢

转载自blog.csdn.net/zl5186888/article/details/127007999
今日推荐