@Conditional及Spring Boot的派生注解如@ConditionOnClass完成;
INF/spring.factories文件中,如:
自动装配顺序
starter:
1、这个场景需要使用到的依赖是什么?2、如何编写自动配置
3、模式:启动器只用来做依赖导入;
专门来写一个自动配置模块;
启动器依赖自动配置;别人只需要引入启动器(starter)
mybatis-spring-boot-starter;自定义启动器名-spring-boot-starter
步骤:
1)、启动器模块
2)、自动配置模块
@ConfigurationProperties(prefix = "zhou.hello") public class HelloProperties { private String prefix; private String suffix; public String getPrefix() { return prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getSuffix() { return suffix; } public void setSuffix(String suffix) { this.suffix = suffix; } }
public class HelloService { HelloProperties helloProperties; public HelloProperties getHelloProperties() { return helloProperties; } public void setHelloProperties(HelloProperties helloProperties) { this.helloProperties = helloProperties; } public String sayHellAtguigu(String name){ return helloProperties.getPrefix()+"-" +name + helloProperties.getSuffix(); } }
@Configuration @ConditionalOnWebApplication //web应用才生效 @EnableConfigurationProperties(HelloProperties.class) public class HelloServiceAutoConfiguration { @Autowired HelloProperties helloProperties; @Bean public HelloService helloService(){ HelloService service = new HelloService(); service.setHelloProperties(helloProperties); return service; } }
新建和配置classpath下META-INF/spring.factories文件:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.atguigu.starter.HelloServiceAutoConfiguration更多SpringBoot整合示例
https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples
文章来源: SpringBoot自定义Starter