Springboot 实现自动装配

SpringBoot由Pivotal团队在2013年开始研发、2014年4月发布第一个版本的全新开源的轻量级框架。基于Spring4.0设计,它不仅继承了Spring框架原有的优秀特性,还通过简化配置来进一步简化了Spring应用的整个搭建和开发过程。另外SpringBoot通过集成大量的框架使得依赖包的版本冲突,以及引用的不稳定性等问题得到了很好的解决。

Springboot 给我们带来了新Spring应用的初始搭建以及开发过程。它使用了特定的方式来进行配置,可以使开发人员不再需要定义样板化的配置。通过这种方式,Spring Boot致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者。

使用Springboot进行Java Web开发,只需引用Springboot提供的spring-boot-starter-parent及spring-boot-starter-web两个依赖,再加上一个SpringApplication#run等简单的配置即可搭建好一个Web开发环境,极大的简化了环境的搭建,提高开发效率。

1.自动装配实现原理

Springboot为我们自动引入了开发所需的对应依赖以及相关bean,其实现自动装配核心主要在@SpringBootApplication以及SpringApplication#run方法

@SpringBootApplication //Springboot核心注解
public class Application {

    public static void main(String[] args) {
        
        SpringApplication.run(Application.class, args);
    }

}

 @SpringBootApplication的核心是@EnableAutoConfiguration

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
		@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {

	
	@AliasFor(annotation = EnableAutoConfiguration.class)
	Class<?>[] exclude() default {};

	
	@AliasFor(annotation = EnableAutoConfiguration.class)
	String[] excludeName() default {};

	
	@AliasFor(annotation = ComponentScan.class, attribute = "basePackages")
	String[] scanBasePackages() default {};

	
	@AliasFor(annotation = ComponentScan.class, attribute = "basePackageClasses")
	Class<?>[] scanBasePackageClasses() default {};

}

 @EnableAutoConfiguration通过@Import引入了AutoConfigurationImportSelector类,它实现了对注解@EnableAutoConfiguration的主要处理逻辑

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {

	String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";

	
	Class<?>[] exclude() default {};

	
	String[] excludeName() default {};

}

 其中getCandidateConfigurations 实现了自动装配的核心文件spring.factories的加载,它会在类路径下加载文件META-INF/spring.factories,读取需要进行自动转配的类信息,提供给Springboot进行加载

protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
		List<String> configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(),
				getBeanClassLoader());
		Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you "
				+ "are using a custom packaging, make sure that file is correct.");
		return configurations;
	}

下面是spring-boot 2.1.8.RELEASE jar包中的spring.factories文件内容,文件中的类信息都会在应用启动时会被加载进Spring Context中,我们自定义实现的SpringApplicationRunListener、ApplicationContextInitializer也可通过在工程的classpath路径下新建META/spring.factories文件,按照下列方式添加,自定义的bean也会被加载到Springboot容器中

# PropertySource Loaders
org.springframework.boot.env.PropertySourceLoader=\
org.springframework.boot.env.PropertiesPropertySourceLoader,\
org.springframework.boot.env.YamlPropertySourceLoader

# Run Listeners
org.springframework.boot.SpringApplicationRunListener=\
org.springframework.boot.context.event.EventPublishingRunListener

# Error Reporters
org.springframework.boot.SpringBootExceptionReporter=\
org.springframework.boot.diagnostics.FailureAnalyzers

# Application Context Initializers
org.springframework.context.ApplicationContextInitializer=\
org.springframework.boot.context.ConfigurationWarningsApplicationContextInitializer,\
org.springframework.boot.context.ContextIdApplicationContextInitializer,\
org.springframework.boot.context.config.DelegatingApplicationContextInitializer,\
org.springframework.boot.web.context.ServerPortInfoApplicationContextInitializer

# Application Listeners
org.springframework.context.ApplicationListener=\
org.springframework.boot.ClearCachesApplicationListener,\
org.springframework.boot.builder.ParentContextCloserApplicationListener,\
org.springframework.boot.context.FileEncodingApplicationListener,\
org.springframework.boot.context.config.AnsiOutputApplicationListener,\
org.springframework.boot.context.config.ConfigFileApplicationListener,\
org.springframework.boot.context.config.DelegatingApplicationListener,\
org.springframework.boot.context.logging.ClasspathLoggingApplicationListener,\
org.springframework.boot.context.logging.LoggingApplicationListener,\
org.springframework.boot.liquibase.LiquibaseServiceLocatorApplicationListener

# Environment Post Processors
org.springframework.boot.env.EnvironmentPostProcessor=\
org.springframework.boot.cloud.CloudFoundryVcapEnvironmentPostProcessor,\
org.springframework.boot.env.SpringApplicationJsonEnvironmentPostProcessor,\
org.springframework.boot.env.SystemEnvironmentPropertySourceEnvironmentPostProcessor

# Failure Analyzers
org.springframework.boot.diagnostics.FailureAnalyzer=\
org.springframework.boot.diagnostics.analyzer.BeanCurrentlyInCreationFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.BeanDefinitionOverrideFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.BeanNotOfRequiredTypeFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.BindFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.BindValidationFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.UnboundConfigurationPropertyFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.ConnectorStartFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.NoSuchMethodFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.NoUniqueBeanDefinitionFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.PortInUseFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.ValidationExceptionFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.InvalidConfigurationPropertyNameFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.InvalidConfigurationPropertyValueFailureAnalyzer

# FailureAnalysisReporters
org.springframework.boot.diagnostics.FailureAnalysisReporter=\
org.springframework.boot.diagnostics.LoggingFailureAnalysisReporter

在SpringApplication的run方法中也会去加载spring.factories文件中的相关类并进行实例化。执行run方法前会初始化SpringApplication对象,其中就会加载spring.factories中定义的ApplicationContextInitializer,SpringApplicationRunListener

public SpringApplication(ResourceLoader resourceLoader, Class... primarySources) {
        this.sources = new LinkedHashSet();
        this.bannerMode = Mode.CONSOLE;
        this.logStartupInfo = true;
        this.addCommandLineProperties = true;
        this.addConversionService = true;
        this.headless = true;
        this.registerShutdownHook = true;
        this.additionalProfiles = new HashSet();
        this.isCustomEnvironment = false;
        this.resourceLoader = resourceLoader;
        Assert.notNull(primarySources, "PrimarySources must not be null");
        this.primarySources = new LinkedHashSet(Arrays.asList(primarySources));
        this.webApplicationType = WebApplicationType.deduceFromClasspath();
        this.setInitializers(this.getSpringFactoriesInstances(ApplicationContextInitializer.class));//加载spring.factoies文件中的定义的ApplicationContextInitializer
        this.setListeners(this.getSpringFactoriesInstances(ApplicationListener.class));//加载spring.factoies定义的SpringApplicationRunListener
        this.mainApplicationClass = this.deduceMainApplicationClass();
    }

2.自定义自动装配实现

实现自定义自动装配需要创建两个工程,greeting-spring-boot-starter,springbooot-autoconfiguration,其中starter的命名可参考springboot官方规范。

greeting-spring-boot-starter: starter只是一个空的项目,用于提供对自动配置模块的依赖,以及一些其他的依赖

springbooot-autoconfiguration: 自动配置工程,需要引入自动配置依赖spring-boot-autoconfigure,spring-boot-configuration-processor

greeting-spring-boot-starter 工程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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.8.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.twp.spring</groupId>
    <artifactId>greeting-spring-boot-starter</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>customer-spring-boot-starter</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>12</java.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>com.twp.spring</groupId>
            <artifactId>springbooot-autoconfiguration</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>12</source>
                    <target>12</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

springbooot-autoconfiguration 中需要实例化的服务类

package com.twp.spring.server;

import com.twp.spring.properties.GreetingServerProperties;

public class GreetingServer {

    private GreetingServerProperties properties;

    public String greet(){

        return properties.getTarget() + ":" + properties.getMessage();
    }

    public GreetingServerProperties getProperties() {
        return properties;
    }

    public void setProperties(GreetingServerProperties properties) {
        this.properties = properties;
    }
}

GreetingServerProperties属性类

package com.twp.spring.properties;

import org.springframework.boot.context.properties.ConfigurationProperties;

import java.io.Serializable;

@ConfigurationProperties(prefix = "greeting")
public class GreetingServerProperties implements Serializable {

    private static final long serialVersionUID = -225936785539739342L;

    private String target;

    private String message;

    public String getTarget() {
        return target;
    }

    public void setTarget(String target) {
        this.target = target;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

自动配置类

package com.twp.spring.configuration;

import com.twp.spring.properties.GreetingServerProperties;
import com.twp.spring.server.GreetingServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableConfigurationProperties(GreetingServerProperties.class)
@ConditionalOnClass(GreetingServer.class)
@ConditionalOnProperty(prefix = "greeting",value = "enabled",matchIfMissing = true)
public class GreetingServerAutoConfiguration {

    @Autowired
    private GreetingServerProperties properties;

    @Bean("greeting")
    public GreetingServer greeting(){
        GreetingServer greetingServer = new GreetingServer();
        greetingServer.setProperties(properties);
        return greetingServer;
    }
}

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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.8.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.twp.spring</groupId>
    <artifactId>springbooot-autoconfiguration</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>springbooot-autoconfiguration</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>12</java.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>12</source>
                    <target>12</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

在spring.factories文件中配置自动配置类

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.twp.spring.configuration.GreetingServerAutoConfiguration

执行mvn clean install,先将自动配置工程进行打包,再打包starter工程

在其他工程中引入starter工程,进行测试

<dependency>
    <groupId>com.twp.spring</groupId>
    <artifactId>greeting-spring-boot-starter</artifactId>
    <version>0.0.1-SNAPSHOT</version>
</dependency>
greeting:
  message: "Hello AutoConfiguration"
  target: "张飞"

测试接口

@Slf4j
@RestController
public class GreetingController {

    @Autowired
    private GreetingServer greetingServer;

    @GetMapping("/greet")
    public String greeting(){
        log.info("Greeting:{}",greetingServer.greet());
        return greetingServer.greet();
    }
}

请求接口结果:

这样就简单实现了自动配置,更加规范的starter编写,可以参考Springboot官方提供的各个组件的starter,如redis,mongoDB等。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值