springboot知识点整合

springboot是什么

Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。

在我看来springboot最大好处就是简化配置,以前一个SpringMvc项目需要在xml配置各种东西,现在简化了很多配置,提高了开发效率

springboot是如何自动配置的

一般我的启动类会有**@SpringBootApplication**注解,这是一个组合注解

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

这里比较重要的是**@EnableAutoConfiguration**

@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
}

@Import是Spring提供的,会注入后面这个类AutoConfigurationImportSelector

其中方法调用为selectImports->getAutoConfigurationEntry->getCandidateConfigurations

往里面看会将META-INF/spring.factories文件里需要的类型获取

获取类的方法会在springboot启动的时候AbstractApplicationContext.refresh()调用。

springboot的启动流程

以tomcat为例来看看springboot的启动加载流程

我们一般会运行main方法SpringApplication.run

先看看SpringApplication的构造方法

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 = WebApplicationType.deduceFromClasspath();
  // 获取初始化的类并set进去
   setInitializers((Collection) getSpringFactoriesInstances(
         ApplicationContextInitializer.class));
  // 获取监听器
   setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
   this.mainApplicationClass = deduceMainApplicationClass();
}

接下来我们主要看springboot的run方法

public ConfigurableApplicationContext run(String... args) {
  // 计时器
   StopWatch stopWatch = new StopWatch();
   stopWatch.start();
   ConfigurableApplicationContext context = null;
   Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
   configureHeadlessProperty();
   SpringApplicationRunListeners listeners = getRunListeners(args);
   listeners.starting();
   try {
      ApplicationArguments applicationArguments = new DefaultApplicationArguments(
            args);
      ConfigurableEnvironment environment = prepareEnvironment(listeners,
            applicationArguments);
      configureIgnoreBeanInfo(environment);
     // 打印banner
      Banner printedBanner = printBanner(environment);
     // 创建context容器
     // AnnotationConfigServletWebServerApplicationContext
      context = createApplicationContext();
      exceptionReporters = getSpringFactoriesInstances(
            SpringBootExceptionReporter.class,
            new Class[] { ConfigurableApplicationContext.class }, context);
      prepareContext(context, environment, listeners, applicationArguments,
            printedBanner);
     // 刷新上下文
      refreshContext(context);
      afterRefresh(context, applicationArguments);
      stopWatch.stop();
      if (this.logStartupInfo) {
         new StartupInfoLogger(this.mainApplicationClass)
               .logStarted(getApplicationLog(), stopWatch);
      }
      listeners.started(context);
      callRunners(context, applicationArguments);
   }
   catch (Throwable ex) {
      handleRunFailure(context, ex, exceptionReporters, listeners);
      throw new IllegalStateException(ex);
   }

   try {
      listeners.running(context);
   }
   catch (Throwable ex) {
      handleRunFailure(context, ex, exceptionReporters, null);
      throw new IllegalStateException(ex);
   }
   return context;
}

我们主要看refreshContext方法,他会调用父类AbstractApplicationContextrefresh方法,里面会调用子类的onRefresh方法,这是一个模板方法模式。接下来看

protected void onRefresh() {
   super.onRefresh();
   try {
   		// 创建web容器
      createWebServer();
   }
   catch (Throwable ex) {
      throw new ApplicationContextException("Unable to start web server", ex);
   }
}

createWebServer方法会创建web容器接下来就能看见创建tomcat的代码了

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);
}
参考

https://mp.weixin.qq.com/s/axRia4KH1YUSVI3WcOfWPg

https://mp.weixin.qq.com/s/TnVL1chwTqlXmlOdcuJCSg

https://mp.weixin.qq.com/s/y6pUTKRCucoeCGmgqwRDow

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
将Kafka与Spring Boot整合是一种常见的开发手段,可以通过导入Spring Boot整合Kafka的starter来实现。你可以在pom.xml文件中添加以下依赖坐标来导入该starter: ``` <dependency> <groupId>org.springframework.kafka</groupId> <artifactId>spring-kafka</artifactId> </dependency> ``` 需要注意的是,直接使用Kafka和使用Spring Boot整合Kafka两种方法虽然原理相同,但在配置、使用和理解上有一些区别。因此,不要混淆这两种方法。例如,在使用Spring Boot整合Kafka时,你可以通过同步监听来实现消息的接收,但这与Kafka本身的ack机制是两个独立的概念。 在完成依赖导入后,你可以创建一个测试类来演示如何使用生产者发送消息。首先,你需要创建一个KafkaTemplate对象,并在测试方法中使用它来发送消息。以下是一个示例代码: ``` @SpringBootTest public class KfKTest { @Autowired private KafkaTemplate<String, String> kafkaTemplate; @Test void pro_test(){ // 构造消息 User user = new User(); user.setName("张三"); user.setAge(20); kafkaTemplate.send("test", user.toString()); } } ``` 在这个示例中,我们使用了@Autowired注解来自动注入KafkaTemplate对象,并在测试方法中通过kafkaTemplate.send方法发送消息到名为"test"的主题。 这就是使用Kafka整合Spring Boot的基本步骤。你可以根据自己的需求进一步扩展和使用Kafka的其他功能。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [SpringBoot整合Kafka](https://blog.csdn.net/m0_37294838/article/details/127253991)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [知识点16--spring boot整合kafka](https://blog.csdn.net/dudadudadd/article/details/125344830)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

久梦歌行

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值