SpringBoot 原理之自动配置

 Spring Boot是使用SpringApplication引导项目启动,SpringApplication类为我们引导项目提供了一种便利的方式——通过main()方法直接启动。大多数情况下,我们可以把项目启动这个任务直接委托给SpringApplication.run方法。

Spring boot关于自动配置的源码在spring-boot-autoconfigure-x.x.x.x.jar中,主要包含了如下图所示的配置(并未截全):

SpringBoot 原理之自动配置_第1张图片

运行原理

在第一次使用spring boot的时候,大家都会惊讶于@SpringBootApplication这个注解,有了它马上就能够让整个应用跑起来。实际上它只是一个组合注解,包含@Configuration、@EnableAutoConfiguration、@ComponentScan这三个注解。

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Configuration
@EnableAutoConfiguration
@ComponentScan
public @interface SpringBootApplication {
    Class[] exclude() default {};
    String[] excludeName() default {};
    @AliasFor(
        annotation = ComponentScan.class,
        attribute = "basePackages"
    )
    String[] scanBasePackages() default {};
    @AliasFor(
        annotation = ComponentScan.class,
        attribute = "basePackageClasses"
    )
    Class[] scanBasePackageClasses() default {};
}

它的核心功能是由@EnableAutoConfiguration这个注解提供的,我们来看看@EnableAutoConfiguration的源代码:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import({EnableAutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {
    Class[] exclude() default {};
    String[] excludeName() default {};
}

这里的关键功能是@Import注解导入的配置功能 

EnableAutoConfigurationImportSelector使用SpringFactoriesLoader.loadFactoryNames方法来扫描具有META-INF/spring.factories文件的jar包,spring-boot-autoconfigure-x.x.x.x.jar里就有一个spring.factories文件,这个文件中声明了有哪些要自动配置。

以MongoDB为例

/*
 * Copyright 2012-2016 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.boot.autoconfigure.mongo;

import java.net.UnknownHostException;

import javax.annotation.PreDestroy;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

/**
 * {@link EnableAutoConfiguration Auto-configuration} for Mongo.
 *
 * @author Dave Syer
 * @author Oliver Gierke
 * @author Phillip Webb
 */
@Configuration
@ConditionalOnClass(MongoClient.class)
@EnableConfigurationProperties(MongoProperties.class)
@ConditionalOnMissingBean(type = "org.springframework.data.mongodb.MongoDbFactory")
public class MongoAutoConfiguration {

	private final MongoProperties properties;

	private final MongoClientOptions options;

	private final Environment environment;

	private MongoClient mongo;

	public MongoAutoConfiguration(MongoProperties properties,
			ObjectProvider options, Environment environment) {
		this.properties = properties;
		this.options = options.getIfAvailable();
		this.environment = environment;
	}

	@PreDestroy
	public void close() {
		if (this.mongo != null) {
			this.mongo.close();
		}
	}

	@Bean
	@ConditionalOnMissingBean
	public MongoClient mongo() throws UnknownHostException {
		this.mongo = this.properties.createMongoClient(this.options, this.environment);
		return this.mongo;
	}

}


你可能感兴趣的:(springboot)