SpringBoot核心【自定义starter】,springboot基础教程

SpringBoot核心【自定义starter】,springboot基础教程,第1张

SpringBoot核心【自定义starter】,springboot基础教程

配置依赖


在pom配置文件中添加如下依赖,增加SpringBoot自身的自动配置作为依赖。

org.springframework.boot

spring-boot-autoconfigure

2.1.4.RELEASE

junit

junit

4.12

org.springframework.boot

spring-boot-configuration-processor

2.1.4.RELEASE

属性配置类


@ConfigurationProperties(prefix = “hello”)

public class HelloServiceProperties {

private static final String MSG = “world”;

private String msg = MSG;

public String getMsg() {

return msg;

}

public void setMsg(String msg) {

this.msg = msg;

}

}

判断依据类


public class HelloService {

private String msg;

public String sayHello(){

return "Hello "+msg;

}

public String getMsg() {

return msg;

}

public void setMsg(String msg) {

this.msg = msg;

}

}

根据此类的存在与否来创建这个类的bean

自动配置类


@Configuration

@EnableConfigurationProperties(HelloServiceProperties.class)

@ConditionalOnClass(HelloService.class)

@ConditionalOnProperty(prefix = “hello”,value =“enabled”,matchIfMissing = true)

public class HelloServiceAutoConfiguration {

@Autowired

private HelloServiceProperties helloServiceProperties;

@Bean

@ConditionalOnMissingBean(HelloService.class)

public HelloService helloService(){

HelloService helloService = new HelloService();

helloService.setMsg(helloServiceProperties.getMsg());

return helloService;

}

}

根据HelloServiceProperties提供的参数,并通过@ConditionalOnClass判断HelloService这个类在类路径中是否存在,且当容器中没有这个Bean的情况下自动配置这个bean。

注册配置


若想自动配置生效,我们需要注册自动配置类,在src/main/resources下新建meta-INF/spring.factories,如下:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.dpb.spring_boot_starter_hello.

《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》

【docs.qq.com/doc/DSmxTbFJ1cmN1R2dB】 完整内容开源分享

HelloServiceAutoConfiguration

如果有多个自动配置,则用“,”隔开。

结构如下:

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5687601.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-17
下一篇2022-12-17

发表评论

登录后才能评论

评论列表(0条)

    保存