自定义SpringBoot Starter
- 引入项目的配置依赖
org.springframework.boot
spring-boot-autoconfigure
2.1.4.RELEASE
- 创建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
com.lhf.springboot
spring-boot-starter-demo
0.0.1-SNAPSHOT
- 编写属性配置文件
#配置自定义的属性信息
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();
}
}