spring-boot-2.0.3不一样系列之源码篇 - springboot源码一,绝对有值得你看的地方

 

前言

  上篇:spring-boot-2.0.3不一样系列之shiro - 搭建篇,实现了spring-boot与shiro的整合,效果大家也看到了,工程确实集成了shiro的认证与授权功能。如果大家能正确搭建起来,并达到了认证和授权的效果,那说明我们会用了,说明我们知其然了;很好,能满足工作中的基本要求了。

  但是这样就够了吗?很显然还是不够的,知其然而不知其所以然是一道瓶颈,如果我们能跨过这道瓶颈,后面的路会越来越坦荡。就拿上篇博客来讲,我们仅仅只是在ShiroConfig类中加入了几个bean配置,怎么就让spring-boot集成了shiro,shiro又是如何做到认证和授权的,等等一些列问题,如果我们去细想的话,真的有很多疑点需要我们去探索。

  既然我们要去探索,势必就要读源码了。源码确实不好读,在我们工作当中,当我们读同事(或者前同事)写的代码的时候,总有那么一句话:草泥马,这是哪个sb写的,萦绕在我们的心头,甚至有时候会发现,这他么是我自己写的啊,哎,我操!有时候读自己写的代码都头疼,更别说看别人写的了。

  说了那么多,我们切入到正题,接下来会有一系列的文章来解析springboot的启动过程,而今天我们只看ShiroApplication类的构造方法。

ShiroApplication类

  入口还是那个熟悉的入口:main函数

  SpringApplication类注释

 View Code

    说的内容大概意思如下:

    SpringApplication用于从java main方法引导和启动Spring应用程序,默认情况下,将执行以下步骤来引导我们的应用程序:

      1、创建一个恰当的ApplicationContext实例(取决于类路径)

      2、注册CommandLinePropertySource,将命令行参数公开为Spring属性

      3、刷新应用程序上下文,加载所有单例bean

      4、触发全部CommandLineRunner bean

    大多数情况下,像SpringApplication.run(ShiroApplication.class, args);这样启动我们的应用,也可以在运行之前创建和自定义SpringApplication实例,具体可以参考注释中示例。

    SpringApplication可以从各种不同的源读取bean。 通常建议使用单个@Configuration类来引导,但是我们也可以通过以下方式来设置资源:

      1、通过AnnotatedBeanDefinitionReader加载完全限定类名

      2、通过XmlBeanDefinitionReader加载XML资源位置,或者是通过GroovyBeanDefinitionReader加载groovy脚本位置

      3、通过ClassPathBeanDefinitionScanner扫描包名称

    也就是说SpringApplication还是做了不少事的,具体实现后续会慢慢讲来,今天的主角只是SpringApplication构造方法。

  SpringApplication构造方法

    源代码如下

复制代码
/**      * Create a new {@link SpringApplication} instance. The application context will load      * beans from the specified primary sources (see {@link SpringApplication class-level}      * documentation for details. The instance can be customized before calling      * {@link #run(String...)}.      * @param resourceLoader the resource loader to use      * @param primarySources the primary bean sources      * @see #run(Class, String[])      * @see #setSources(Set)      */     @SuppressWarnings({ "unchecked", "rawtypes" })     public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {         this.resourceLoader = resourceLoader;         Assert.notNull(primarySources, "PrimarySources must not be null");         this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));         this.webApplicationType = deduceWebApplicationType();         setInitializers((Collection) getSpringFactoriesInstances(                 ApplicationContextInitializer.class));         setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));         this.mainApplicationClass = deduceMainApplicationClass();     }
复制代码

    从注释上来看,就是说创建一个ShiroApplication实例,应用上下文从特定的资源文件中加载bean。可以在调用run之前自定义实例。

    从源码上来看,主要是deduceWebApplicationType();getSpringFactoriesInstances(xxx.class);deduceMainApplicationClass();这三个方法,我们一个一个来看。

    deduceWebApplicatio

50000+
5万行代码练就真实本领
17年
创办于2008年老牌培训机构
1000+
合作企业
98%
就业率

联系我们

电话咨询

0532-85025005

扫码添加微信