SpringBoot基本原理
SpringBoot
可以幫助我們更好的使用Spring
,更快的配置一個可以執行的Spring應用。
SpringBoot
實現自動配置實現的入口是@EnableAutoConfiguration
註解,該註解又通過@Import
註解匯入了AutoConfigurationImportSelector
,在該類中實現了對META-INF/spring.factories
中
org.springframework.boot.autoconfigure.EnableAutoConfiguration
屬性指定的所有配置,如org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration
。
//檔案:spring-boot-autoconfigure-2.1.3.RELEASE.jar!/META-INF/spring.factories
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\
複製程式碼
在CacheAutoConfiguration中,通過條件註解@ConditionalOnXXX
,以及@Import
註解來實現對快取功能的相關Bean
的自動配置。
// 檔案:spring-boot-autoconfigure-2.1.3.RELEASE-sources.jar!/org/springframework/boot/autoconfigure/cache/CacheAutoConfiguration.java
@Configuration
@ConditionalOnClass(CacheManager.class)
@ConditionalOnBean(CacheAspectSupport.class)
@ConditionalOnMissingBean(value = CacheManager.class, name = "cacheResolver")
@EnableConfigurationProperties(CacheProperties.class)
@AutoConfigureAfter({ CouchbaseAutoConfiguration.class, HazelcastAutoConfiguration.class,
HibernateJpaAutoConfiguration.class, RedisAutoConfiguration.class })
@Import(CacheConfigurationImportSelector.class)
public class CacheAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public CacheManagerCustomizers cacheManagerCustomizers(
ObjectProvider<CacheManagerCustomizer<?>> customizers) {
return new CacheManagerCustomizers(
customizers.orderedStream().collect(Collectors.toList()));
}
複製程式碼
實現自己的AutoConfiguration
在實際開發過程中,我們可能需要將公司內部的,或者Spring官方還不支援的第三方類庫整合到我們的專案中。但是為了重用,最好能夠按照SpringBoot的自動配置來配置。
第一步:引入Spring官方依賴
專案的pom檔案:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!-- 和Spring官方的自動配置做區分 -->
<groupId>geektime.spring.hello</groupId>
<artifactId>geektime-spring-boot-autoconfigure</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>geektime-spring-boot-autoconfigure</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<spring-boot.version>2.1.3.RELEASE</spring-boot.version>
</properties>
<!-- 引入Spring官方的配置管理 -->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- 引入SpringBoot的自動配置模組 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<!-- 自己的定義第三方依賴 -->
<dependency>
<groupId>geektime.spring.hello</groupId>
<artifactId>greeting</artifactId>
<version>0.0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
複製程式碼
第二步:編寫Java Configuration,並新增條件註解
Spring支援的條件註解:
- 條件註解@Conditional
- 類條件@ConditionalOnClass,@ConditionalOnMissingClass
- 屬性條件@ConditionalOnProperty
- Bean 條件@ConditionalOnBean,@ConditionalOnMissingBean,@ConditionalOnSingleCandidate
- 資源條件@ConditionalOnResource
- Web 應⽤用條件@ConditionalOnWebApplication,@ConditionalOnNotWebApplication
- 其他條件@ConditionalOnExpression,@ConditionalOnJava,@ConditionalOnJndi
Java Configuration程式碼如下:
@Configuration
@ConditionalOnClass(GreetingApplicationRunner.class)
public class GreetingAutoConfiguration {
@Bean
@ConditionalOnMissingBean(GreetingApplicationRunner.class)
@ConditionalOnProperty(name = "greeting.enabled", havingValue = "true", matchIfMissing = true)
public GreetingApplicationRunner greetingApplicationRunner() {
return new GreetingApplicationRunner();
}
}
複製程式碼
第三步:定位自動配置
在當前專案的resource
目錄下的META-INF
目錄下建立spring.factories
檔案,內容如下:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
geektime.spring.hello.greeting.GreetingAutoConfiguration
複製程式碼
第四步:定義自動配置的執行順序
主要的註解有:
- @AutoConfigureBefore
- @AutoConfigureAfter
- @AutoConfigureOrder
一般不需要,具體使用可以參考Spring官方的自動配置。
如何在不支援SpringBoot的老版本Spring中實現SpringBoot
如果在老版本的Spring中實現類似SpringBoot的自動配置功能,則需要使用Spring的擴充套件點機制,原理可以參考博文Spring框架的擴充套件點。
新增一個Configuration:
@Configuration
public class GreetingAutoConfiguration {
@Bean
public static GreetingBeanFactoryPostProcessor greetingBeanFactoryPostProcessor() {
return new GreetingBeanFactoryPostProcessor();
}
}
複製程式碼
自定義一個BeanFactoryPostProcessor
實現類似條件註解的功能:
@Slf4j
public class GreetingBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
boolean hasClass = ClassUtils.isPresent("geektime.spring.hello.greeting.GreetingApplicationRunner",
GreetingBeanFactoryPostProcessor.class.getClassLoader());
if (!hasClass) {
log.info("GreetingApplicationRunner is NOT present in CLASSPATH.");
return;
}
if (beanFactory.containsBeanDefinition("greetingApplicationRunner")) {
log.info("We already have a greetingApplicationRunner bean registered.");
return;
}
register(beanFactory);
}
private void register(ConfigurableListableBeanFactory beanFactory) {
if (beanFactory instanceof BeanDefinitionRegistry) {
GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
beanDefinition.setBeanClass(GreetingApplicationRunner.class);
((BeanDefinitionRegistry) beanFactory)
.registerBeanDefinition("greetingApplicationRunner",
beanDefinition);
} else {
beanFactory.registerSingleton("greetingApplicationRunner",
new GreetingApplicationRunner());
}
}
}
複製程式碼