文档的意义在于以后方便自己回忆 可执行例子点我
springboot starter 的作用感觉就是定义一些公用对象或者是常用设置,导入对应的starter后,你就可以使用它们仿佛就是自己定义的一样。
app 启动的,没啥用,启动后,可以http://localhost:8080/theclass 点击使用
resource是模拟第三方资源的,没啥用
autoconfigure用于定义你的配置,核心
starter 引入autoconfigure,以及其它第三方资源,这个可以和autoconfigure合并在一起的
package lol.yi;
import com.example.EmbeddedAcmeService;
import com.example.MyService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
@Configuration
// Some conditions
public class MyAutoConfiguration {
// Auto-configured beans
@Configuration
@ConditionalOnClass(EmbeddedAcmeService.class)
static class EmbeddedConfiguration {
@Bean
@ConditionalOnMissingBean
public EmbeddedAcmeService embeddedAcmeService() {
return new EmbeddedAcmeService();
}
}
@Configuration
static class MyServiceConfiguration {
@Bean
@Primary
@ConditionalOnMissingBean(MyService.class)
public MyService myService() {
return new MyService();
}
}
}
建立了这么多文档,核心代码就这个。
官方原文 auto-configuration classes use @ConditionalOnClass
and @ConditionalOnMissingBean
annotations. This ensures that auto-configuration applies only when relevant classes are found and when you have not declared your own@Configuration
.
@ConditionalOnClass
and @ConditionalOnMissingBean这两个注解的确保自动配置应用在,你有相关的类被发现且自己没有声明自己的配置。(大概就是备胎的意思)。
还有很重要一点,这个里面的bean如果你的componentScan路径没有它,那么你需要一些别的设置
你需要在你自己的autoconfigure的项目的资源文件中创建META-INF/spring.factories,然后在里面把你的配置类加进去
如org.springframework.boot.autoconfigure.EnableAutoConfiguration=lol.yi.MyAutoConfiguration
官方文档有这一段,在这个章节 48.2 Locating Auto-configuration Candidates
参考了部分别人文档,以及官方文档,就翻译了吧