阅读更多
1 条件注解
1.1 Class Conditions
@ConditionalOnClass:classpath中包含指定类时,包含配置@ConditionalOnMissingClass:classpath中不包含指定类时,包含配置
- 其中
value属性填写的是真实的类(Class对象),name属性,填写的是类名
1.2 Bean Conditions
@ConditionalOnBean:ApplicationContext中包含指定Bean时,包含配置@ConditionalOnMissingBean:ApplicationContext中不包含指定Bean时,包含配置
- 其中
value属性按类型匹配Bean,name属性按名字匹配Bean - 条件是否成立,只取决于Spring在处理注解时的
ApplicationContext - 如果
@ConditionalOnBean和@ConditionalOnMissingBean标记在类上,且类中无一条件匹配,那么类上标记的@Configuration将会被忽略(换言之,该类本身不会生成Bean)
1.3 Property Conditions
@ConditionalOnProperty:允许基于Spring Environment属性包含配置。使用prefix和name属性指定应检查的属性。默认情况下,匹配存在且不等于false的任何属性。您还可以使用havingValue和matchIfMissing属性创建更高级的检查
1.4 Resource Conditions
@ConditionalOnResource:允许存在特定资源时包含配置。可以使用常用的Spring约定来指定资源,例如:file:/home/user/test.dat
1.5 Web Application Conditions
@ConditionalOnWebApplication:当应用是Web Application时,包含配置@ConditionalOnNotWebApplication:当应用不是Web Application时,包含配置Web Application是指包含了WebApplicationContext,或StandardServletEnvironment的应用
1.6 SpEL Expression Conditions
@ConditionalOnExpression:基于SpEL expression的结果,决定是否包含配置
1.7 Starter的结构
一般而言,一个Spring-Boot-Starter应用,一般包含如下两个模块:
autoconfigure module:用于包含配置代码starter module:依赖于autoconfigure module,以及其他应用的依赖
- 我们也可以将以上两个模块合成一个模块
2 META-INF/spring.factories
一些三方项目如何与Spring集成,并且无需任何配置就可以自动注入到我们应用的上下文中?答案就是:基于约定。
META-INF/spring.factories是spring-autoconfig的核心配置文件
org.springframework.boot.diagnostics.FailureAnalyzerorg.springframework.boot.autoconfigure.EnableAutoConfigurationorg.springframework.context.ApplicationContextInitializerorg.springframework.context.ApplicationListenerorg.springframework.boot.env.EnvironmentPostProcessororg.springframework.boot.autoconfigure.AutoConfigurationImportListenerorg.springframework.boot.autoconfigure.AutoConfigurationImportFilterorg.springframework.boot.autoconfigure.template.TemplateAvailabilityProviderorg.springframework.test.context.TestExecutionListenerorg.springframework.test.context.ContextCustomizerFactoryorg.springframework.boot.env.PropertySourceLoaderorg.springframework.boot.SpringApplicationRunListenerorg.springframework.boot.diagnostics.FailureAnalysisReporter
3 todo
ConfigurationProperties 属性必须有get/set方法