SpringBoot自定义Starter及使用
作者:「已注销」
这篇文章主要介绍了SpringBoot自定义Starter及使用,Starter是Spring Boot中的一个非常重要的概念,Starter相当于模块,它能将模块所需的依赖整合起来并对模块内的Bean根据环境进行自动配置,需要的朋友可以参考下
1 创建一个自定义Starter项目
CustomConfig
@Configuration @EnableConfigurationProperties(value = CustomProperties.class) // 使配置类生效 @ConditionalOnProperty(prefix = "mmw.config", name = "enable", havingValue = "true") // 自动装配条件 public class CustomConfig { @Resource private CustomProperties customProperties; @Bean public ConfigService defaultCustomConfig() { return new ConfigService(customProperties.getAge(), customProperties.getName(), customProperties.getInfo()); } }
CustomProperties
@ConfigurationProperties(prefix = "mmw.config") public class CustomProperties { private Integer age; private String name; private String info; // getter/setter }
ConfigService
public class ConfigService { private Integer age; private String name; private String info; public ConfigService(Integer age, String name, String info) { this.age = age; this.name = name; this.info = info; } public String showConfig() { return "ConfigService{" + "age=" + age + ", name='" + name + '\'' + ", info='" + info + '\'' + '}'; } }
META-INF/spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.mmw.demo.config.CustomConfig
2 创建一个测试springBoot项目
application.yml
mmw: config: enable: true age: 26 name: 'my custom starter' info: 'custom web info...' server: port: 8081 spring: application: name: customStarterTestDemo
TestController
@RestController public class TestController { @Resource private ConfigService configService; @GetMapping("/test") public String test() { return configService.showConfig(); } }
3 测试自动装配
到此这篇关于SpringBoot自定义Starter及使用的文章就介绍到这了,更多相关自定义Starter内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!