在我们的日常开发工作中,经常会有一些独立于业务之外的配置模块,我们经常将其放到一个特定的包下,然后如果另一个工程需要复用这块功能的时候,需要将代码硬拷贝到另一个工程,重新集成一遍,麻烦至极。如果我们将这些可独立于业务代码之外的功配置模块封装成一个个starter,复用的时候只需要将其在pom中引用依赖即可,SpringBoot为我们完成自动装配。
SpringBoot提供的starter以spring-boot-starter-xxx
的方式命名的。官方建议自定义的starter使用xxx-spring-boot-starter
命名规则。以区分SpringBoot生态提供的starter。
1、新建一个SpringBoot工程;
添加POM依赖:
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency>
2.定义一个实体类映射配置信息
@Data @ConfigurationProperties(prefix = "demo") public class DemoProperties { private String sayWhat; private String toWho; }
3.定义一个Service
@Service public class DemoService { private String sayWhat; private String toWho; public DemoService() { } public DemoService(String sayWhat, String toWho) { this.sayWhat = sayWhat; this.toWho = toWho; } public String say() { return sayWhat + "! " + toWho; } }
4.定义一个配置类
@Configuration @EnableConfigurationProperties(value = DemoProperties.class) @ConditionalOnProperty(prefix = "demo", name = "isOpen", havingValue = "true") public class DemoConfig { @Autowired private DemoProperties properties; @Bean public DemoService demoService() { return new DemoService(properties.getSayWhat(), properties.getToWho()); } }
5.创建spring.factories文件
在resources的META-INF目录下新建spring.factories文件,定义内容:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.demo.demospringbootstarter.config.DemoConfig
6.测试
1)、引入依赖:
<dependency> <groupId>com.demo</groupId> <artifactId>demo-spring-boot-starter</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency>
2)、配置文件:
在application.properties配置文件中增加如下配置项:
demo.isOpen=true demo.say-what=hello demo.to-who=bill gates
3)、编写测试类:
@RestController public class DemoController { @Resource private DemoService demoService; @GetMapping("/demo") public String demo() { return demoService.say(); } }
4)、运行调试;
参考资料: