springboot启动原理 通俗面试_spring高级面试题

springboot启动原理 通俗面试_spring高级面试题importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;/***Helloworld!**/@SpringBootApplicationpublicclassApp{publicstaticvoidmain(String[]args){Syst.

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * Hello world!
 *
 */
@SpringBootApplication
public class App 
{
    public static void main( String[] args )
    {

        System.out.println( "Hello World!" );

        SpringApplication.run(App.class,args);
    }
}

一、Spring  SPI机制,自动装配:

启动类使用@SpringApplication注解,看一下注解代码:

代码中使用@EnableAutoConfiguration以及@ComponentScan自动装配

其中注解@EnableAutoConfiguration使用了@Import加载,最后使用了SpringFactoriesLoader反射出maven中META-INF下spring.factories。

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

package org.springframework.boot.autoconfigure;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.context.annotation.Import;

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


//
public class AutoConfigurationImportSelector ...{

...
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {

//加载类路径下面  META-INF/spring.factories
        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;
    }

}


public abstract class SpringFactoriesLoader {
    public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";

.....

public static List<String> loadFactoryNames(Class<?> factoryClass, @Nullable ClassLoader classLoader) {
        String factoryClassName = factoryClass.getName();
        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 = PropertiesLoaderUtils.loadProperties(resource);
                    Iterator var6 = properties.entrySet().iterator();

                    while(var6.hasNext()) {
                        Entry<?, ?> entry = (Entry)var6.next();
                        List<String> factoryClassNames = Arrays.asList(StringUtils.commaDelimitedListToStringArray((String)entry.getValue()));
                        result.addAll((String)entry.getKey(), factoryClassNames);
                    }
                }

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

....
}

感兴趣的老铁,可以看一下java 的SPI和Spring的SPI,自动装配机制

二、SpringBoot启动时通过执行main方法中的SpringApplication.run方法去启动,在run方法中调用了SpringApplication的构造方法,在该构造方法中加载了META-INFA\spring.factories文件配置的ApplicationContextInitializer的实现类和ApplicationListenerr的实现类: 

springboot启动原理 通俗面试_spring高级面试题

 SpringApplication.run(..,..)

springboot启动原理 通俗面试_spring高级面试题 

 

二、ApplicationContextInitializer 这个类当springboot上下文Context初始化完成后会调用。                   ApplicationListener当springboot启动时事件change后都会触发。

三、SpringApplication实例构造完之后会调用它的run方法,在run方法中作了以下几步重要操作:

springboot启动原理 通俗面试_spring高级面试题
1. 获取事件监听器SpringApplicationRunListener类型,并且执行starting()方法

2. 准备环境,并且把环境跟spring上下文绑定好,并且执行environmentPrepared()方法

3. 创建上下文,根据项目类型创建上下文

4. 执行spring的启动流程扫描并且初始化单实列bean

四、通过@SpringBootApplication注解将ClassPath路径下所有的META-INF\spring.factories文件中的EnableAutoConfiguration实例注入到IOC容器中

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/171555.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • aarch64指令集_AArch64应用程序级编程模型

    aarch64指令集_AArch64应用程序级编程模型根据实现选择,体系结构支持多级执行特权,由从EL0到EL3的不同异常级别表示。EL0对应于最低的特权级别,通常被描述为无特权。应用层程序员模型是在EL0上执行软件的程序员模型。系统软件决定异常级别,因此决定软件运行的特权级别。当操作系统同时支持EL1和EL0执行时,应用程序通常在EL0上运行。允许操作系统以唯一的或共享的方式将系统资源分配给应用程序。从其他进程中提供一定程度的保护,因此有助于保护操…

    2022年10月17日
    4
  • yarn的安装和使用(yarn安装mysql)

    升级yarn升级指定版本(例:升级到v1.22.10版本)yarnupgradev1.22.10npmyarn安装/升级最新版本npminstallyarn@latest-g查看yarn历史版本npmviewyarnversions–json[“0.1.0″,”0.1.1″,”0.1.2″,”0.1.3″,”0.15.1″,”0.16.0″,”0.16.1″,”0.17.0”,”0.17…

    2022年4月13日
    71
  • java深拷贝和浅拷贝_java数组copyof

    java深拷贝和浅拷贝_java数组copyof实现拷贝有几点:1)实现Cloneable接口2)重写Object类中的clone方法,并将可见性从protect改为public3)克隆需要调用super.clone(),也就是Object的实现方法浅拷贝和深拷贝的区别:浅拷贝是指拷贝对象时仅仅拷贝对象本身(包括对象中的基本变量),而不拷贝对象包含的引用指向的对象。深拷贝不仅拷贝对象本身,而且拷贝对象包含的引用指向的所有对象。以下代码说明了浅拷…

    2022年9月26日
    3
  • bootstrap使用教程_bootstrap 教程

    bootstrap使用教程_bootstrap 教程bootStrap是干嘛的?有什么用处?我们在开发前端页面的时候,如果每一个按钮、样式、处理浏览器兼容性的代码都要自己从零开始去写,那就太浪费时间了。所以我们需要一个框架,帮我们实现一个页面的基础部分和解决一些繁琐的细节,只要在它的基础上进行个性化定制就可以了。Bootstrap就是这样一个简洁、直观、强悍的前端开发框架,只要学习并遵守它的标准,即使是没有学过网页设计的开发者,也能做出很…

    2022年10月9日
    4
  • 格林威治时间格式 字符串_string字符串转数组的方法

    格林威治时间格式 字符串_string字符串转数组的方法今天要处理从前端传来的日期参数,穿来的是一个GMT格式的字符串,类似于这种ThuMay18201800:00:00GMT+0800(中国标准时间)将字符串转成java.util.Date类型的做法是使用SimpleDateFormat,SimpleDateFormat有一个pattern参数用于匹配字符串里的时间数据。我按照网上方法将pattern设置为&quot;EEEMMMdd…

    2022年10月3日
    2
  • 利用数据库邮件服务实现监控和预警

    利用数据库邮件服务实现监控和预警

    2021年11月28日
    56

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号