SpringBoot创建自定义Starter代码实例
作者:Heloise_yangyuchang
这篇文章主要介绍了SpringBoot创建自定义Starter代码实例,自定义 Starter 是一种在软件开发中常用的技术,它可以帮助开发者快速搭建项目的基础框架和配置,可以将一些常用的功能、依赖和配置封装成一个可复用的模块,方便在不同的项目中使用,需要的朋友可以参考下
自定义SpringBoot Starter
引入项目的配置依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>2.1.4.RELEASE</version>
</dependency>
创建xxxService类
完成相关的操作逻辑
DemoService.java
@Data
public class DemoService{
private String str1;
private String str2;
}
定义xxxProperties类
属性配置类,完成属性配置相关的操作,比如设置属性前缀,用于在application.properties中配置
//指定项目在属性文件中配置的前缀为str,即可以在属性文件中通过 str.str1=springboot,就可以改变属性类字段 str1 的值了
@SuppressWarnings("ConfigurationProperties")
@ConfigurationProperties(prefix = "str")
@Data
public class DemoProperties {
public static final String DEFAULT_STR1 = "SpringBoot ";
public static final String DEFAULT_STR2 = "Starter";
private String str1 = DEFAULT_STR1;
private String str2 = DEFAULT_STR2;
}
定义xxxAutoConfiguration类
自动配置类,用于完成Bean创建等工作
// 定义 java 配置类
@Configuration
//引入DemoService
@ConditionalOnClass({DemoService.class})
// 将 application.properties 的相关的属性字段与该类一一对应,并生成 Bean
@EnableConfigurationProperties(DemoProperties.class)
public class DemoAutoConfiguration {
// 注入属性类
@Autowired
private DemoProperties demoProperties;
@Bean
// 当容器没有这个 Bean 的时候才创建这个 Bean
@ConditionalOnMissingBean(DemoService.class)
public DemoService helloworldService() {
DemoService demoService= new DemoService();
demoService.setStr1(demoProperties.getStr1());
demoService.setStr2(demoProperties.getStr2());
return demoService;
}
}
在resources下创建目录META-INF
在 META-INF 目录下创建 spring.factories,在SpringBoot启动时会根据此文件来加载项目的自动化配置类
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.demo.springboot.config.DemoAutoConfiguration
其他项目中使用自定义的Starter
<!--引入自定义Starter-->
<dependency>
<groupId>com.lhf.springboot</groupId>
<artifactId>spring-boot-starter-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
编写属性配置文件
#配置自定义的属性信息 str.str1=str1 str.str2=str2
写注解使用
@RestController
public class StringController {
@Autowired
private DemoService demoService; //引入自定义Starter中的DemoService
@RequestMapping("/")
public String addString(){
return demoService.getStr1()+ demoService.getStr2();
}
}
到此这篇关于SpringBoot创建自定义Starter代码实例的文章就介绍到这了,更多相关SpringBoot自定义Starter内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
