SpringBoot中自定义start

SpringBoot中自定义start:

1.分析原生的start

1.每一个xxx-start中都有一个xxx-autoconfigure
2.每一个xxx-autoconfigure都有一个spring-boot-start
3.每一个xxx-autoconfigure都有一个META-INF的文件夹里面都有一个spring.factories,
里面配置了EnableAutoConfiguration的值,使项目一启动就加载指定的自动配置类
4.编写自动配置类:xxxAutoconfigurtaion-->xxxProperties(并进行配置绑定)
,在进行组件的配置
5.流程是:引入starter--->xxxAutoconfiguration--->容器中放入组件--->绑定xxxProperties--->配置项

代码:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>2.4.1</version>
<scope>compile</scope>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot</artifactId>
<version>2.4.1</version>
<scope>compile</scope>
</dependency>

spring-boot-autoconfigure的目录结构
spring.factories文件
在这里插入图片描述

2.自定义start

1.创建一个空的工程,添加一个maven项目和一个springboot的项目,目录结构如下:
自定义的start和自定义的start-autoconfigure
2.在hellospringbootstarter这个模块下的pom文件中引入hello-spring-boot-starter-autoconfigure这个模块的坐标
在这里插入图片描述
3.接下来在hello-spring-boot-starter-autoconfigure这个模块中编写三个类
目录结构
4.在HelloService中自动注入helloProperties这个对象并引入该对象的属性在sayHello这个方法中.

public class HelloService {

    @Autowired
    HelloProperties helloProperties;

    public String sayHello(String userName){
        return helloProperties.getPrefix()+": "+userName+"->"+helloProperties.getSuffix();
    }
}

5.在 HelloProperties这个类中加入注解@ConfigurationProperties(prefix = “hello”)进行配置绑定

@ConfigurationProperties(prefix = "hello")
public class HelloProperties {
    private String prefix;
    private String suffix;

    public String getPrefix() {
        return prefix;
    }

    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }

    public String getSuffix() {
        return suffix;
    }

    public void setSuffix(String suffix) {
        this.suffix = suffix;
    }
}

6.最后编写HelloServiceAutoConfiguration类,将该类变为一个配置类,并将HelloService加入容器中

@Configuration
@EnableConfigurationProperties(value = {HelloProperties.class})
public class HelloServiceAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean(value = {HelloService.class})
    public HelloService helloService(){
        HelloService helloService = new HelloService();
        return helloService;
    }

7.最后在hello-spring-boot-starter-autoconfigure这个模块的resources目录下创建一个META-INF文件夹编写一个spring.factories文件配置好使项目启动自动加载的配置类

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.boot.hello.auto.HelloServiceAutoConfiguration
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值