springboot源碼分析-SpringApplication

来源:https://www.cnblogs.com/mori-luck/archive/2019/04/01/10634349.html
-Advertisement-
Play Games

SpringApplication SpringApplication類提供了一種方便的方法來引導從main()方法啟動的Spring應用程式 SpringBoot 包掃描註解源碼分析 我們來看下spring boot裡面是怎麼創建applicationContext的: 我們來看下webAppli ...


SpringApplication

SpringApplication類提供了一種方便的方法來引導從main()方法啟動的Spring應用程式

 

SpringBoot 包掃描註解源碼分析

 

@SpringBootApplication
public class Springbootv2Application {
   public static void main(String[] args) {
      //創建ApplicationContext並啟動
      new SpringApplication(Springbootv2Application.class).run(args);
   }
}

 

/**
 * Run the Spring application, creating and refreshing a new
 * {@link ApplicationContext}.
 * @param args the application arguments (usually passed from a Java main method)
 * @return a running {@link ApplicationContext}
 */
public ConfigurableApplicationContext run(String... args) {
   StopWatch stopWatch = new StopWatch();
   //記錄應用啟動時間
   stopWatch.start();
   ConfigurableApplicationContext context = null;
   Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
    
   configureHeadlessProperty();
   //啟動SpringApplicationRunListener
   SpringApplicationRunListeners listeners = getRunListeners(args);
   listeners.starting();
   try {
      ApplicationArguments applicationArguments = new DefaultApplicationArguments(
            args);
      ConfigurableEnvironment environment = prepareEnvironment(listeners,
            applicationArguments);
      configureIgnoreBeanInfo(environment);
       //列印banner
      Banner printedBanner = printBanner(environment);
      //創建applicationContext 我們這次的重點在這裡面
      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;
}

 

我們來看下spring boot裡面是怎麼創建applicationContext的:

protected ConfigurableApplicationContext createApplicationContext() {
   Class<?> contextClass = this.applicationContextClass;
   if (contextClass == null) {
      try {
         //主要是根據webApplicationType這個屬性
         switch (this.webApplicationType) {
         case SERVLET:
            //如果是SERVLET創建"org.springframework.boot.
            //web.servlet.context.AnnotationConfigServletWebServerApplicationContext"
            contextClass = Class.forName(DEFAULT_SERVLET_WEB_CONTEXT_CLASS);
            break;
         case REACTIVE:
             //如果是REACTIVE創建"org.springframework.
        //boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext"
            contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS);
            break;
         default:
            //預設是創建org.springframework.context.
            //annotation.AnnotationConfigApplicationContext
            contextClass = Class.forName(DEFAULT_CONTEXT_CLASS);
         }
      }
      catch (ClassNotFoundException ex) {
         throw new IllegalStateException(
               "Unable create a default ApplicationContext, "
                     + "please specify an ApplicationContextClass",
               ex);
      }
   }
   return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);
}

 

我們來看下webApplicationType這個屬性是怎麼取值的:

static WebApplicationType deduceFromClasspath() {
    /**
    **  如果程式中有org.springframework.web.reactive.DispatcherHandler這個類且沒有
    ** org.springframework.web.servlet.DispatcherServlet和  
    ** org.glassfish.jersey.servlet.ServletContainer 這兩類那麼就是REACTIVE
    **/
   if (ClassUtils.isPresent(WEBFLUX_INDICATOR_CLASS, null)
         && !ClassUtils.isPresent(WEBMVC_INDICATOR_CLASS, null)
         && !ClassUtils.isPresent(JERSEY_INDICATOR_CLASS, null)) {
      return WebApplicationType.REACTIVE;
   }
   //SERVLET_INDICATOR_CLASSES = { "javax.servlet.Servlet",
    //      "org.springframework.web.context.ConfigurableWebApplicationContext" }
    // 如果程式中這兩個類有一個不存在就是NONE
   for (String className : SERVLET_INDICATOR_CLASSES) {
      if (!ClassUtils.isPresent(className, null)) {
         return WebApplicationType.NONE;
      }
   }
    //如果上面都不是那就是SERVLET
   return WebApplicationType.SERVLET;
}

 

根據上面的代碼我們可以看出如果我們不引入reactive和web的依賴那麼我們的程式預設就是使用的NONE,對應的

ApplicationContext就是AnnotationConfigApplicationContext這個類,接下來我們再看下這個類的構造方法:

public AnnotationConfigApplicationContext() {
   //創建一個AnnotatedBeanDefinitionReader
   this.reader = new AnnotatedBeanDefinitionReader(this);
   this.scanner = new ClassPathBeanDefinitionScanner(this);
}
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
   Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
   Assert.notNull(environment, "Environment must not be null");
   this.registry = registry;
   this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);
   //註冊AnnotationConfigProcessors 重點看這裡
   AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
}
public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
      BeanDefinitionRegistry registry, @Nullable Object source) {
​
   DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
   if (beanFactory != null) {
      if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
         beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
      }
      if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
         beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
      }
   }
​
   Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8);
​
   // 如果registry不包含ConfigurationClassPostProcessor這個類信息時註冊到registry
   if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
      RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
      def.setSource(source);
      beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
   }
   //註冊AutowiredAnnotationBeanPostProcessor
   if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
      RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
      def.setSource(source);
      beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
   }
​
   // Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor.
   if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {
      RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
      def.setSource(source);
      beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
   }
​
   // Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor.
   //是否需要支持jpa 是的話註冊對應的bean
   if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {
      RootBeanDefinition def = new RootBeanDefinition();
      try {
         def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME,
               AnnotationConfigUtils.class.getClassLoader()));
      }
      catch (ClassNotFoundException ex) {
         throw new IllegalStateException(
               "Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex);
      }
      def.setSource(source);
      beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME));
   }
    
   if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) {
      RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class);
      def.setSource(source);
      beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME));
   }
​
   if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) {
      RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);
      def.setSource(source);
      beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));
   }
​
   return beanDefs;
}

 

看到這裡我們先記著我們註冊了ConfigurationClassPostProcessor 和AutowiredAnnotationBeanPostProcessor這兩個類,我們繼續往下看,我們現在來看refreshContext(context)的流程我們根據代碼可以看到

protected void refresh(ApplicationContext applicationContext) {
   Assert.isInstanceOf(AbstractApplicationContext.class, applicationContext);
    //刷新applicationContext
   ((AbstractApplicationContext) applicationContext).refresh();
}

 

上面代碼調用到ApplicationContext的refresh 因為我們程式根據依賴推導出我們的ApplicationContext是AnnotationConfigApplicationContext這個類,所以我們來看下AnnotationConfigApplicationContext的refresh方法:

因為AnnotationConfigApplicationContext是繼承於AbstractApplicationContext這個類的,所以我們的refresh就是AbstractApplicationContext的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.
         //調用程式里的BeanFactoryPostProcessors
         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 boot是怎麼掃描包的 所以我們重點看invokeBeanFactoryPostProcessors這個方法,在這之前我們先記住ConfigurationClassPostProcessor的類圖:

因為方法太長所以我去掉了一些不是這次重點的代碼:

public static void invokeBeanFactoryPostProcessors(
      ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
​
   // Invoke BeanDefinitionRegistryPostProcessors first, if any.
   Set<String> processedBeans = new HashSet<>();
    ...
      // Do not initialize FactoryBeans here: We need to leave all regular beans
      // uninitialized to let the bean factory post-processors apply to them!
      // Separate between BeanDefinitionRegistryPostProcessors that implement
      // PriorityOrdered, Ordered, and the rest.
      List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
​
      // First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
      //記得我們之前註冊的ConfigurationClassPostProcessor嗎,因為他是實現了BeanDefinitionRegistryPostProcessor介面的,所以這裡會被取到
      String[] postProcessorNames =
            beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
      for (String ppName : postProcessorNames) {
          // ConfigurationClassPostProcessor 類同時也實現了PriorityOrdered介面
         if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
             //創建ConfigurationClassPostProcessor對象並把它加到list中
            currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
            processedBeans.add(ppName);
         }
      }
      sortPostProcessors(currentRegistryProcessors, beanFactory);
      registryProcessors.addAll(currentRegistryProcessors);
     //調用方法
      invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
      currentRegistryProcessors.clear();
​
     ...
   beanFactory.clearMetadataCache();
}

 

繼續跟蹤代碼的話會調用到ConfigurationClassPostProcessor的processConfigBeanDefinitions方法

public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
   List<BeanDefinitionHolder> configCandidates = new ArrayList<>();
   String[] candidateNames = registry.getBeanDefinitionNames();
​
   ...
​
   // Parse each @Configuration class
   ConfigurationClassParser parser = new ConfigurationClassParser(
         this.metadataReaderFactory, this.problemReporter, this.environment,
         this.resourceLoader, this.componentScanBeanNameGenerator, registry);
​
   Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);
   Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());
   do {
      //這裡我們只有我們的啟動類Springbootv2Application 這個parser是ConfigurationClassParser所以我們進入它的parse方法
      parser.parse(candidates);
      parser.validate();
​
     ...
}

 

最後會進入下麵這方法

protected void processConfigurationClass(ConfigurationClass configClass) throws IOException {
   ...
   // Recursively process the configuration class and its superclass hierarchy.
   //獲得我們的啟動類全名 xxx.xxx.Springbootv2Application
   SourceClass sourceClass = asSourceClass(configClass);
   do {
       //spring 的命名規則就是do開頭的就是真正幹活的地方
      sourceClass = doProcessConfigurationClass(configClass, sourceClass);
   }
   while (sourceClass != null);
​
   this.configurationClasses.put(configClass, configClass);
}

 

protected final SourceClass doProcessConfigurationClass(ConfigurationClass configClass, SourceClass sourceClass)
      throws IOException {
    ...
   // Process any @ComponentScan annotations
   //獲取啟動類的componentScans屬性
   Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(
         sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
   if (!componentScans.isEmpty() &&
         !this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
      for (AnnotationAttributes componentScan : componentScans) {
         // The config class is annotated with @ComponentScan -> perform the scan immediately
          //掃描beanDefinition
         Set<BeanDefinitionHolder> scannedBeanDefinitions =
               this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());
         // Check the set of scanned definitions for any further config classes and parse recursively if needed
         for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
            BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
            if (bdCand == null) {
               bdCand = holder.getBeanDefinition();
            }
            if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
               parse(bdCand.getBeanClassName(), holder.getBeanName());
            }
         }
      }
   }
​
  ...
   return null;
}

 

下麵就是重點了:

public Set<BeanDefinitionHolder> parse(AnnotationAttributes componentScan, final String declaringClass) {
   ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(this.registry,
         componentScan.getBoolean("useDefaultFilters"), this.environment, this.resourceLoader);
    
   Class<? extends BeanNameGenerator> generatorClass = componentScan.getClass("nameGenerator");
   boolean useInheritedGenerator = (BeanNameGenerator.class == generatorClass);
   scanner.setBeanNameGenerator(useInheritedGenerator ? this.beanNameGenerator :
         BeanUtils.instantiateClass(generatorClass));
    //配置scanner的屬性
   ScopedProxyMode scopedProxyMode = componentScan.getEnum("scopedProxy");
   if (scopedProxyMode != ScopedProxyMode.DEFAULT) {
      scanner.setScopedProxyMode(scopedProxyMode);
   }
   else {
      Class<? extends ScopeMetadataResolver> resolverClass = componentScan.getClass("scopeResolver");
      scanner.setScopeMetadataResolver(BeanUtils.instantiateClass(resolverClass));
   }
    
   scanner.setResourcePattern(componentScan.getString("resourcePattern"));
​
   for (AnnotationAttributes filter : componentScan.getAnnotationArray("includeFilters")) {
      for (TypeFilter typeFilter : typeFiltersFor(filter)) {
         scanner.addIncludeFilter(typeFilter);
      }
   }
   for (AnnotationAttributes filter : componentScan.getAnnotationArray("excludeFilters")) {
      for (TypeFilter typeFilter : typeFiltersFor(filter)) {
         scanner.addExcludeFilter(typeFilter);
      }
   }
​
   boolean lazyInit = componentScan.getBoolean("lazyInit");
   if (lazyInit) {
      scanner.getBeanDefinitionDefaults().setLazyInit(true);
   }
​
   Set<String> basePackages = new LinkedHashSet<>();
   String[] basePackagesArray = componentScan.getStringArray("basePackages");
   for (String pkg : basePackagesArray) {
      String[] tokenized = StringUtils.tokenizeToStringArray(this.environment.resolvePlaceholders(pkg),
            ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
      Collections.addAll(basePackages, tokenized);
   }
   for (Class<?> clazz : componentScan.getClassArray("basePackageClasses")) {
      basePackages.add(ClassUtils.getPackageName(clazz));
   }
   //重點就是這裡,如果我們沒有配置basePackages的話那麼這裡就取啟動類的包名
   if (basePackages.isEmpty()) {
      basePackages.add(ClassUtils.getPackageName(declaringClass));
   }
​
   scanner.addExcludeFilter(new AbstractTypeHierarchyTraversingFilter(false, false) {
      @Override
      protected boolean matchClassName(String className) {
         return declaringClass.equals(className);
      }
   });
   //這裡就是掃描包下的類,這裡是數組如果我們有配置的話就是我們配置的包,沒有的話就是啟動類的包名
   return scanner.doScan(StringUtils.toStringArray(basePackages));
}

 

private Set<BeanDefinition> scanCandidateComponents(String basePackage) {
   Set<BeanDefinition> candidates = new LinkedHashSet<>();
   try {
       //掃描包下的所有**/*.class
      String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
            resolveBasePackage(basePackage) + '/' + this.resourcePattern;
      Resource[] resources = getResourcePatternResolver().getResources(packageSearchPath);
      boolean traceEnabled = logger.isTraceEnabled();
      boolean debugEnabled = logger.isDebugEnabled();
      for (Resource resource : resources) {
         if (traceEnabled) {
            logger.trace("Scanning " + resource);
         }
         if (resource.isReadable()) {
            try {
               MetadataReader metadataReader = getMetadataReaderFactory().getMetadataReader(resource);
                //這裡會排除掉不需要註冊的bean
               if (isCandidateComponent(metadataReader)) {
                  ScannedGenericBeanDefinition sbd = new ScannedGenericBeanDefinition(metadataReader);
                  sbd.setResource(resource);
                  sbd.setSource(resource);
                  if (isCandidateComponent(sbd)) {
                     if (debugEnabled) {
                        logger.debug("Identified candidate component class: " + resource);
                     }
                     candidates.add(sbd);
                  }
                  else {
                     if (debugEnabled) {
                        logger.debug("Ignored because not a concrete top-level class: " + resource);
                     }
                  }
               }
               else {
                  if (traceEnabled) {
                     logger.trace("Ignored because not matching any filter: " + resource);
                  }
               }
            }
            catch (Throwable ex) {
               throw new BeanDefinitionStoreException(
                     "Failed to read candidate component class: " + resource, ex);
            }
         }
         else {
            if (traceEnabled) {
               logger.trace("Ignored because not readable: " + resource);
            }
         }
      }
   }
   catch (IOException ex) {
      throw new BeanDefinitionStoreException("I/O failure during classpath scanning", ex);
   }
   return candidates;
}

 

源碼太多,我這裡去掉一些這次不是重點關註的代碼,有興趣的可以自己去看下


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 文件打開模式 | 打開模式 | 執行操作 | | | | | 'r' | 以只讀方式打開文件(預設) | | 'w' | 以寫入的方式打開文件,會覆蓋已存在的文件 | | 'x' | 如果文件已經存在,使用此模式打開將引發異常 | | 'a' | 以寫入模式打開,如果文件存在,則在末尾追加寫入 | ...
  • 背景 在平時的項目中,幾乎都會用到比較兩個字元串時候相等的問題,通常是用==或者equals()進行,這是在數據相對比較少的情況下是沒問題的,當資料庫中的數據達到幾十萬甚至是上百萬千萬的數據需要從中進行匹配的時候,傳統的方法顯示是不行的,影響匹配的效率,時間也會要很久,用戶體驗很差的,今天就要介紹一 ...
  • 2.單元測試相關 # 測試一個工程 $ ./manage.py test # 只測試某個應用 $ ./manage.py test app --keepdb # 只測試一個Case $ ./manage.py test animals.test.StudentTestCase 3.資料庫 資料庫名: ...
  • 簡介 JSON Web Token(縮寫 JWT)是目前最流行的跨域認證解決方案。 "JSON Web Token 入門教程 阮一峰" ,這篇文章可以幫你瞭解JWT的概念。本文重點講解Spring Boot 結合 jwt ,來實現前後端分離中,介面的安全調用。 快速上手 之前的文章已經對 Sprin ...
  • 前言 開心一刻 一隻被二哈帶偏了的柴犬,我只想弄死隔壁的二哈 what:是什麼 BeanFactoryPostProcessor介面很簡單,只包含一個方法 推薦大家直接去讀它的源碼註釋,說的更詳細、更好理解 簡單來說,BeanFactoryPostProcessor是spring對外提供的介面,用來 ...
  • 題意 "題目鏈接" Sol 神仙題。。Orz yyb 考慮點分治,那麼每次我們只需要統計以當前點為$LCA$的點對之間的貢獻以及$LCA$到所有點的貢獻。 一個很神仙的思路是,對於任意兩個點對的路徑上的顏色,我們只統計里根最近的那個點的貢獻。 有了這個思路我們就可以瞎搞了,具體的細節很繁瑣,但是大概 ...
  • 測試代碼筆記如下: 附: ...
  • 1、棧和隊列 操作 增查改刪重點 插入刪除先進先出 -->隊列先進後出 -->棧2、鏈表 寫之前先畫圖存儲數據的方式 通過指針將所有的數據鏈在一起數據結構的目的 管理存儲數據 方便快速查找使用 鏈表定義 鏈式存儲的線性表 一對一的關係結構體 指針 函數 迴圈 結構體複習:struct 點運算符(結構 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...