自定义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中配置
@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创建等工作
@Configuration
@ConditionalOnClass({DemoService.class})
@EnableConfigurationProperties(DemoProperties.class)
public class DemoAutoConfiguration {
@Autowired
private DemoProperties demoProperties;
@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;
@RequestMapping("/")
public String addString(){
return demoService.getStr1()+ demoService.getStr2();
}
}