0
  • 聊天消息
  • 系统消息
  • 评论与回复
登录后你可以
  • 下载海量资料
  • 学习在线课程
  • 观看技术视频
  • 写文章/发帖/加入社区
创作中心

完善资料让更多小伙伴认识你,还能领取20积分哦,立即完善>

3天内不再提示

SpringBoot的核心注解2

jf_78858299 来源:Java知音 作者:小毛毛 2023-04-07 14:34 次阅读

他会调用 ((AbstractApplicationContext) applicationContext).refresh();方法,我们点进来看

public void refresh() throws BeansException, IllegalStateException {
   synchronized (this.startupShutdownMonitor) {
      // Prepare this context for refreshing.
      prepareRefresh();

      // Tell the subclass to refresh the internal bean factory.
      ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

      // Prepare the bean factory for use in this context.
      prepareBeanFactory(beanFactory);

      try {
         // Allows post-processing of the bean factory in context subclasses.
         postProcessBeanFactory(beanFactory);

         // Invoke factory processors registered as beans in the context.
         invokeBeanFactoryPostProcessors(beanFactory);

         // Register bean processors that intercept bean creation.
         registerBeanPostProcessors(beanFactory);

         // Initialize message source for this context.
         initMessageSource();

         // Initialize event multicaster for this context.
         initApplicationEventMulticaster();

         // Initialize other special beans in specific context subclasses.
         onRefresh();

         // Check for listener beans and register them.
         registerListeners();

         // Instantiate all remaining (non-lazy-init) singletons.
         finishBeanFactoryInitialization(beanFactory);

         // Last step: publish corresponding event.
         finishRefresh();
      }

      catch (BeansException ex) {
         if (logger.isWarnEnabled()) {
            logger.warn("Exception encountered during context initialization - " +
                  "cancelling refresh attempt: " + ex);
         }

         // Destroy already created singletons to avoid dangling resources.
         destroyBeans();

         // Reset 'active' flag.
         cancelRefresh(ex);

         // Propagate exception to caller.
         throw ex;
      }

      finally {
         // Reset common introspection caches in Spring's core, since we
         // might not ever need metadata for singleton beans anymore...
         resetCommonCaches();
      }
   }
}

这点代码似曾相识啊 没错,就是一个spring的bean的加载过程我在,解析springIOC加载过程的时候介绍过这里面的方法,如果你看过Spring源码的话 ,应该知道这些方法都是做什么的。现在我们不关心其他的,我们来看一个方法叫做 onRefresh();方法

protected void onRefresh() throws BeansException {
   // For subclasses: do nothing by default.
}

他在这里并没有实现,但是我们找他的其他实现,我们来找

图片

我们既然要找Tomcat那就肯定跟web有关,我们可以看到有个ServletWebServerApplicationContext

@Override
protected void onRefresh() {
   super.onRefresh();
   try {
      createWebServer();
   }
   catch (Throwable ex) {
      throw new ApplicationContextException("Unable to start web server", ex);
   }
}

我们可以看到有一个createWebServer();方法他是创建web容器的,而Tomcat不就是web容器,那他是怎么创建的呢,我们继续看

private void createWebServer() {
   WebServer webServer = this.webServer;
   ServletContext servletContext = getServletContext();
   if (webServer == null && servletContext == null) {
      ServletWebServerFactory factory = getWebServerFactory();
      this.webServer = factory.getWebServer(getSelfInitializer());
   }
   else if (servletContext != null) {
      try {
         getSelfInitializer().onStartup(servletContext);
      }
      catch (ServletException ex) {
         throw new ApplicationContextException("Cannot initialize servlet context",
               ex);
      }
   }
   initPropertySources();
}

factory.getWebServer(getSelfInitializer());他是通过工厂的方式创建的

public interface ServletWebServerFactory {

   WebServer getWebServer(ServletContextInitializer... initializers);

}

可以看到 它是一个接口,为什么会是接口。因为我们不止是Tomcat一种web容器。

图片

我们看到还有Jetty,那我们来看TomcatServletWebServerFactory

@Override
public WebServer getWebServer(ServletContextInitializer... initializers) {
   Tomcat tomcat = new Tomcat();
   File baseDir = (this.baseDirectory != null) ? this.baseDirectory
         : createTempDir("tomcat");
   tomcat.setBaseDir(baseDir.getAbsolutePath());
   Connector connector = new Connector(this.protocol);
   tomcat.getService().addConnector(connector);
   customizeConnector(connector);
   tomcat.setConnector(connector);
   tomcat.getHost().setAutoDeploy(false);
   configureEngine(tomcat.getEngine());
   for (Connector additionalConnector : this.additionalTomcatConnectors) {
      tomcat.getService().addConnector(additionalConnector);
   }
   prepareContext(tomcat.getHost(), initializers);
   return getTomcatWebServer(tomcat);
}

那这块代码,就是我们要寻找的内置Tomcat,在这个过程当中,我们可以看到创建Tomcat的一个流程。因为run方法里面加载的东西很多,所以今天就浅谈到这里。如果不明白的话, 我们在用另一种方式来理解下,

大家要应该都知道stater举点例子

<dependency>
    <groupId>org.springframework.boot<span class="hljs-name"groupId>
    <artifactId>spring-boot-starter-data-redis<span class="hljs-name"artifactId>
<span class="hljs-name"dependency>
<dependency>
    <groupId>org.springframework.boot<span class="hljs-name"groupId>
    <artifactId>spring-boot-starter-freemarker<span class="hljs-name"artifactId>
<span class="hljs-name"dependency>

所以我们不防不定义一个stater来理解下,我们做一个需求,就是定制化不同的人跟大家说你们好,我们来看

<parent>
    <groupId>org.springframework.boot<span class="hljs-name"groupId>
    <artifactId>spring-boot-starter-parent<span class="hljs-name"artifactId>
    <version>2.1.4.RELEASE<span class="hljs-name"version>
    <relativePath/>
<span class="hljs-name"parent>
<groupId>com.zgw<span class="hljs-name"groupId>
<artifactId>gw-spring-boot-srater<span class="hljs-name"artifactId>
<version>1.0-SNAPSHOT<span class="hljs-name"version>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot<span class="hljs-name"groupId>
        <artifactId>spring-boot-autoconfigure<span class="hljs-name"artifactId>
    <span class="hljs-name"dependency>
<span class="hljs-name"dependencies>

我们先来看maven配置写入版本号,如果自定义一个stater的话必须依赖spring-boot-autoconfigure这个包,我们先看下项目目录

图片

public class GwServiceImpl  implements GwService{
    @Autowired
    GwProperties properties;

    @Override
    public void Hello()
    {
        String name=properties.getName();
        System.out.println(name+"说:你们好啊");
    }
}

我们做的就是通过配置文件来定制name这个是具体实现

@Component
@ConfigurationProperties(prefix = "spring.gwname")
public class GwProperties {

    String name="zgw";

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

这个类可以通过@ConfigurationProperties读取配置文件

@Configuration
@ConditionalOnClass(GwService.class)  //扫描类
@EnableConfigurationProperties(GwProperties.class) //让配置类生效
public class GwAutoConfiguration {

    /**
    * 功能描述 托管给spring
    * @author zgw
    * @return
    */
    @Bean
    @ConditionalOnMissingBean
    public GwService gwService()
    {
        return new GwServiceImpl();
    }
}

这个为配置类,为什么这么写因为,spring-boot的stater都是这么写的,我们可以参照他仿写stater,以达到自动配置的目的,然后我们在通过spring.factories也来进行配置

org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.gw.GwAutoConfiguration

然后这样一个简单的stater就完成了,然后可以进行maven的打包,在其他项目引入就可以使用,在这里列出代码地址

声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉
  • XML
    XML
    +关注

    关注

    0

    文章

    183

    浏览量

    32936
  • spring
    +关注

    关注

    0

    文章

    332

    浏览量

    14161
  • Boot
    +关注

    关注

    0

    文章

    142

    浏览量

    35244
  • 注解
    +关注

    关注

    0

    文章

    18

    浏览量

    2638
  • SpringBoot
    +关注

    关注

    0

    文章

    172

    浏览量

    106
收藏 人收藏

    评论

    相关推荐

    SpringBoot配置Mybatis的2个错误和修正

    SpringBoot】配置Mybatis错误
    发表于 04-19 10:31

    一文解析SpringBoot2整合SSM框架

    SpringBoot2整合SSM框架详解
    发表于 06-09 16:43

    怎样去使用springboot

    怎样去使用springboot呢?学习springboot需要懂得哪些?
    发表于 10-25 07:13

    Spring Boot常用注解与使用方式

    企业开发项目SpringBoot已经是必备框架了,其中注解是开发中的小工具(谁处可见哦),用好了开发效率大大提升,当然用错了也会引入缺陷。
    的头像 发表于 07-08 10:57 1095次阅读

    求一种SpringBoot定时任务动态管理通用解决方案

    SpringBoot的定时任务的加强工具,实现对SpringBoot原生的定时任务进行动态管理,完全兼容原生@Scheduled注解,无需对原本的定时任务进行修改
    的头像 发表于 02-03 09:49 549次阅读

    一个无需注解SpringBoot API文档生成神器

    如果提交的表单是 application/x-www-form-urlencoded 类型的key/value格式,你可以在 SpringBoot 端通过在 @param 参数后添加字段解释或者在相关的JavaBean对象里面添加解释:
    的头像 发表于 03-13 09:38 590次阅读

    什么是 SpringBoot

    本文从为什么要有 `SpringBoot`,以及 `SpringBoot` 到底方便在哪里开始入手,逐步分析了 `SpringBoot` 自动装配的原理,最后手写了一个简单的 `start` 组件,通过实战来体会了 `
    的头像 发表于 04-07 11:28 1027次阅读
    什么是 <b class='flag-5'>SpringBoot</b>?

    SpringBoot常用注解及使用方法1

    基于 SpringBoot 平台开发的项目数不胜数,与常规的基于`Spring`开发的项目最大的不同之处,SpringBoot 里面提供了大量的注解用于快速开发,而且非常简单,基本可以做到开箱即用! 那
    的头像 发表于 04-07 11:51 445次阅读

    SpringBoot常用注解及使用方法2

    基于 SpringBoot 平台开发的项目数不胜数,与常规的基于Spring开发的项目最大的不同之处,SpringBoot 里面提供了大量的注解用于快速开发,而且非常简单,基本可以做到开箱即用!
    的头像 发表于 04-07 11:52 407次阅读

    Springboot常用注解合集

    前几章,在系统启动类里面,都加入了此启动注解,此注解是个组合注解,包括了`@SpringBootConfiguration`、`@EnableAutoConfiguration`和`@ComponentScan`
    的头像 发表于 04-07 14:27 522次阅读
    <b class='flag-5'>Springboot</b>常用<b class='flag-5'>注解</b>合集

    SpringBoot常用注解及原理

    SpringBootConfiguration继承自@Configuration,二者功能也一致,标注当前类是配置类, 并会将当前类内声明的一个或多个以@Bean注解标记的方法的实例纳入到spring容器中,并且实例名就是方法名。
    的头像 发表于 04-07 14:30 407次阅读

    SpringBoot核心注解1

    今天跟大家来探讨下SpringBoot核心注解@SpringBootApplication以及run方法,理解下springBoot为什么不需要XML,达到零配置
    的头像 发表于 04-07 14:34 491次阅读
    <b class='flag-5'>SpringBoot</b>的<b class='flag-5'>核心</b><b class='flag-5'>注解</b>1

    springboot核心注解

    Spring Boot 是基于 Spring 框架的开源框架,它可以帮助开发者快速构建、部署和运行独立的、生产级的 Spring 应用程序。Spring Boot 提供了一系列核心注解,这些注解可以
    的头像 发表于 11-23 09:23 290次阅读

    一个注解搞定SpringBoot接口防刷

    技术要点:springboot的基本知识,redis基本操作,
    的头像 发表于 11-28 10:46 221次阅读

    SpringBoot核心注解由几个注解组成

    简化应用程序开发的注解,其中核心注解包括 @SpringBootApplication、@RestController、@RequestMapping、@Autowired、@ComponentScan
    的头像 发表于 12-03 15:09 337次阅读