前几天我们学会了如何创建springboot项目今天我们说一下他是怎么运行的为什么不需要我们再去编写繁重的配置文件的

@SpringBootApplication

首先我们看一下这个注解,他是用来标注在主程序的,表明他是一个springboot项目

@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 {
}

点进@SpringBootApplication注解后我们重点关注最后三个注解

@ComponentScan(包扫描)
  • component是组件,scan是扫描,所以这个注解的含义就是用来扫描组件的,

  • componentScan就是扫描所标注的类所在包下的所有需要注入的组件,将其注入,这里他是在@SpringBootApplication 中体现的,所以这个注解会自动注入所有在主程序所在包下的组件

  • 以前在ssm项目中我们需要去配置我们的包扫描

  
<context:component-scan base-package="com.xxx"></context:component-scan>
@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 {};
}

这里我们关注两个注解

一、@AutoConfigurationPackage

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

在这个注解中,主要是获取我们注解所在包下的组件去进行注册

  
 static class Registrar implements ImportBeanDefinitionRegistrar, DeterminableImports {
Registrar() {
}

//metadata是我们注解所在的元信息
public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
//看这里 将我们注解所在包下所有的组件去进行注册
AutoConfigurationPackages.register(registry, (new AutoConfigurationPackages.PackageImport(metadata)).getPackageName());
}

public Set<Object> determineImports(AnnotationMetadata metadata) {
return Collections.singleton(new AutoConfigurationPackages.PackageImport(metadata));
}
}

register方法:通过AutoConfigurationPackages去对包下的组件进行注册

  
 private static final String BEAN = AutoConfigurationPackages.class.getName();

public static void register(BeanDefinitionRegistry registry, String... packageNames) {
//先判断整个BEAN有没有被注册
if (registry.containsBeanDefinition(BEAN)) {
//获取bean的定义
BeanDefinition beanDefinition = registry.getBeanDefinition(BEAN);
//通过bean获取构造函数的参数值
ConstructorArgumentValues constructorArguments = beanDefinition.getConstructorArgumentValues();
//添加参数值,
constructorArguments.addIndexedArgumentValue(0, addBasePackages(constructorArguments, packageNames));
} else {
//创建一个新的bean的定义
GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
//设置bean的类型为AutoConfigurationPackages类型
beanDefinition.setBeanClass(AutoConfigurationPackages.BasePackages.class);
beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(0, packageNames);
beanDefinition.setRole(2);
//进行bean的注册
registry.registerBeanDefinition(BEAN, beanDefinition);
}
}

二、@Import({AutoConfigurationImportSelector.class})

装配我们的 自动配置导入选择器

我们点进去这个类,下面有一个方法getAutoConfigurationEntry 获取自动装配的入口、

  
protected AutoConfigurationImportSelector.AutoConfigurationEntry getAutoConfigurationEntry(AutoConfigurationMetadata autoConfigurationMetadata, AnnotationMetadata annotationMetadata) {
if (!this.isEnabled(annotationMetadata)) {
return EMPTY_ENTRY;
} else {
AnnotationAttributes attributes = this.getAttributes(annotationMetadata);
List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);
configurations = this.removeDuplicates(configurations);
Set<String> exclusions = this.getExclusions(annotationMetadata, attributes);
this.checkExcludedClasses(configurations, exclusions);
configurations.removeAll(exclusions);
configurations = this.filter(configurations, autoConfigurationMetadata);
this.fireAutoConfigurationImportEvents(configurations, exclusions);
return new AutoConfigurationImportSelector.AutoConfigurationEntry(configurations, exclusions);
}
}

这个方法他主要是获取了configurations的一个集合在这我们点进去getCandidateConfigurations方法

  
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
List<String> configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.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;
}

我们首先看他这个红色报错信息:在META-INF/spring.factories中没有找到自动配置类。根据他的错误信息我们可以得出他是从META-INF/spring.factories获取我们的自动配置信息的

我们也可以在点进这个loadFactoryNames这个方法

   public static List<String> loadFactoryNames(Class<?> factoryClass, @Nullable ClassLoader classLoader) {
String factoryClassName = factoryClass.getName();
//调用了下面的方法loadSpringFactories
return (List)loadSpringFactories(classLoader).getOrDefault(factoryClassName, Collections.emptyList());
}

private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
MultiValueMap<String, String> result = (MultiValueMap)cache.get(classLoader);
if (result != null) {
return result;
} else {
try {
//根据类加载器去获取配置文件里的信息
Enumeration<URL> urls = classLoader != null ? classLoader.getResources("META-INF/spring.factories") : ClassLoader.getSystemResources("META-INF/spring.factories");
LinkedMultiValueMap result = new LinkedMultiValueMap();

while(urls.hasMoreElements()) {
URL url = (URL)urls.nextElement();
UrlResource resource = new UrlResource(url);
//配置信息经过多次转换最终成为properties形式
Properties properties = PropertiesLoaderUtils.loadProperties(resource);
Iterator var6 = properties.entrySet().iterator();
//循环获取所有的配置信息
while(var6.hasNext()) {
Entry<?, ?> entry = (Entry)var6.next();
String factoryClassName = ((String)entry.getKey()).trim();
String[] var9 = StringUtils.commaDelimitedListToStringArray((String)entry.getValue());
int var10 = var9.length;

for(int var11 = 0; var11 < var10; ++var11) {
String factoryName = var9[var11];
result.add(factoryClassName, factoryName.trim());
}
}
}

cache.put(classLoader, result);
return result;
} catch (IOException var13) {
throw new IllegalArgumentException("Unable to load factories from location [META-INF/spring.factories]", var13);
}
}
}

而这个配置文件在哪里呢

在我们项目的External Libraries中找到我们的spring-boot-autoconfigure中

这样就完成我们默认的一些自动装配了

@SpringBootConfiguration

这个方法就比较简单了,表明了这是一个配置类

  @Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface SpringBootConfiguration {
}
 
到这我们三个注解就讲完了,有什么问题请大佬们指明谢谢。

有过挣扎,有过失败,但仍然会爬起来继续战斗

详谈springboot启动类的@SpringBootApplication注解的更多相关文章

  1. springboot系列(三) 启动类中关键注解作用解析

    一.Springboot:请求入口 @SpringBootApplication @EnableAspectJAutoProxy @EnableScheduling @EnableTransactio ...

  2. springboot 启动类CommandLineRunner(转载)

    在Spring boot项目的实际开发中,我们有时需要项目服务启动时加载一些数据或预先完成某些动作.为了解决这样的问题,Spring boot 为我们提供了一个方法:通过实现接口 CommandLin ...

  3. springboot 启动类启动跳转到前端网页404问题的两个解决方案

    前段时间研究springboot 发现使用Application类启动的话, 可以进入Controller方法并且返回数据,但是不能跳转到WEB-INF目录下网页, 前置配置 server: port ...

  4. Springboot启动类及注解说明

    Spring boot的启动是基于main方法的,其主要注解为: 1. @springBootApplication:项目的启动注解,是一个组合注解,包含@SpringbootConfiguratio ...

  5. Springboot测试类之@RunWith注解

    @runWith注解作用: --@RunWith就是一个运行器 --@RunWith(JUnit4.class)就是指用JUnit4来运行 --@RunWith(SpringJUnit4ClassRu ...

  6. SpringBoot学习之@SpringBootApplication注解

    下面是我们经常见到SpringBoot启动类代码: @SpringBootApplicationpublic class DemoApplication extends SpringBootServl ...

  7. SpringBoot启动tomcat源码解读

    一.SpringBoot自动拉起Tomcat 原文链接:http://www.studyshare.cn/blog-front/blog/details/1136 SpringBoot框架是当前比较流 ...

  8. Springboot中使用自定义参数注解获取 token 中用户数据

    使用自定义参数注解获取 token 中User数据 使用背景 在springboot项目开发中需要从token中获取用户信息时通常的方式要经历几个步骤 拦截器中截获token TokenUtil工具类 ...

  9. SpringBoot启动嵌入式tomcat源码解读

    一.SpringBoot自动拉起Tomcat SpringBoot框架是当前比较流行的java后端开发框架,与maven结合大大简化了开发人员项目搭建的步骤,我们知道SpringBoot的启动类启动后 ...

随机推荐

  1. PHP导出成PDF你用哪个插件

    准备工作 首先查询了相关的类库,有FPDF,zendPDF,TcPDF等等.首先看了下先选择了FPDF,可以说除了中文字符以外没有什么问题,中文乱码而且看了下最新版本没有很好的解决方案,所以只能放弃. ...

  2. 设计模式(Java语言)- 简单工厂模式

    简单工厂模式有称为静态工厂模式,属于设计模式中的创建型模式.简单工厂模式通过对外提供一个静态方法来统一为类创建实例.简单工厂模式的目的是实现类与类之间解耦,其次是客户端不需要知道这个对象是如何被穿创建 ...

  3. [ASP.NET Core 3框架揭秘] 文件系统[2]:总体设计

    在<抽象的"文件系统">中,我们通过几个简单的实例演示从编程的角度对文件系统做了初步的体验,接下来我们继续从设计的角度来进一步认识它.这个抽象的文件系统以目录的形式来组 ...

  4. 微擎JS资源请求 403

    微擎JS资源请求 403 1.确认JS是否指定 type ==> text/javascript 2.确认src的路径是否正确,{MODULE_URL}项目的根目录带反斜杠 3.实例:(PS:t ...

  5. 【并发编程】synchronized的使用场景和原理简介

    1. synchronized使用 1.1 synchronized介绍 在多线程并发编程中synchronized一直是元老级角色,很多人都会称呼它为重量级锁.但是,随着Java SE 1.6对sy ...

  6. bat脚本知识总结

    1常用基本命令 1.1 @ 它的作用是让执行窗口中不显示它后面这一行的命令本身 1.2 echo 它其实是一个开关命令,就是说它只有两种状态:打开和关闭.于是就有了echo on 和echo off两 ...

  7. 移动端自动化测试Appium环境搭建(part1-2-3)

    Appium移动端自动化测试相信大家都不陌生,appium的铁哥们是selenium,不管是selenium还是appium,都是调用webdriver来做自动化测试.今天关于appium的介绍我们不 ...

  8. .NET Core 3.0中用 Code-First 方式创建 gRPC 服务与客户端

    .NET Core love gRPC 千呼万唤的 .NET Core 3.0 终于在 9 月份正式发布,在它的众多新特性中,除了性能得到了大大提高,比较受关注的应该是 ASP.NET Core 3. ...

  9. Linux菜鸟——搭建虚拟机环境

    最近在学习Linux搭建服务器,但本人对于Linux一无所知,所以花了两天时间把安装,命令,控制,搭建环境等一系列操作都囫囵吞枣了一遍,但又怕自己记不住太多,所以记录下以前搭建的所有步骤,希望能提醒自 ...

  10. 50.Qt-QJsonDocument读写json

    QJsonDocument: 提供一种读取和写入JSON文档的方法,可以通过它的的成员函数array()或object()检索文档中包含的数组或对象,然后读取JSON数据,或者修改数据. QJsonO ...