SpringBootアノテーションの原則

まず、SpringBootのメイン構成クラスを見てください。

@SpringBootApplication
public class StartEurekaApplication
{
    public static void main(String[] args)
    {
        SpringApplication.run(StartEurekaApplication.class, args);
    }
}

@SpringBootApplicationをクリックして、@ 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) })
public @interface SpringBootApplication {

}

まず、@ SpringBootConfigurationを見てみましょう。

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface SpringBootConfiguration {
}

このアノテーションのメタアノテーションの他に、@ Configurationが1つしかないことがわかります。つまり、このアノテーションは@Configurationと同等であるため、これら2つのアノテーションは同じ効果を持ちます。これにより、いくつかの追加のBeanを登録できます。そしてそれらをインポートします。いくつかの追加の構成。@Configurationの他の機能は、このクラスを追加のXML構成なしで構成クラスに変換することです。したがって、@ SpringBootConfigurationは@Configurationと同等です。@Configurationと入力し、@ Configurationコアが@Componentであることを確認します。これは、Springの構成クラスもSpringのコンポーネントであることを示しています。

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {
    @AliasFor(
        annotation = Component.class
    )
    String value() default "";
}

次の@EnableAutoConfigurationを引き続き確認します。このアノテーションは、自動構成機能を有効にするためのものです。

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

@AutoConfigurationPackageと@Import(EnableAutoConfigurationImportSelector.class)で構成されていることがわかります。最初に@AutoConfigurationPackageについて説明しましょう。つまり、パッケージ内のクラスとサブパッケージ内のクラスが自動的にスキャンされて春になります。コンテナ。

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import({Registrar.class})
public @interface AutoConfigurationPackage {
}

@Importを使用して、コンポーネントをSpringコンテナにインポートします。これがRegistrar.classです。このレジストラを見てください:

    static class Registrar implements ImportBeanDefinitionRegistrar, DeterminableImports {
        Registrar() {
        }

        public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
            AutoConfigurationPackages.register(registry, (new AutoConfigurationPackages.PackageImport(metadata)).getPackageName());
        }

        public Set<Object> determineImports(AnnotationMetadata metadata) {
            return Collections.singleton(new AutoConfigurationPackages.PackageImport(metadata));
        }
    }

スキャンされたパッケージパスを取得するには、上記の方法を使用します。デバッグして特定の値を表示できます。

画像

メタデータとは何ですか?@SpringBootApplicationアノテーションでマークされたDemosbApplicationであることがわかります。これは、メインの構成クラスApplicationです。

画像

実際メイン構成クラス(つまり、@ SpringBootApplicationでマークされたクラス)のパッケージおよびサブパッケージ内のすべてのコンポーネントスキャンされ、Springコンテナーにロードされ ます。したがって、DemoApplicationをプロジェクトの最上位(最も外側のディレクトリ)に配置する必要があります。

アノテーション@Import(AutoConfigurationImportSelector.class)を見てください。@ Importアノテーションは、いくつかのコンポーネントをSpringコンテナにインポートするためのものです。コンポーネントセレクターは次のとおりです:AutoConfigurationImportSelector。

画像

図から、AutoConfigurationImportSelectorがDeferredImportSelectorとImportSelectorを継承していることがわかります。ImportSelectorにはメソッドselectImportsがあります。インポートする必要のあるすべてのコンポーネントを完全なクラス名として返します。これらのコンポーネントはコンテナに追加されます。

public String[] selectImports(AnnotationMetadata annotationMetadata) {
    if (!this.isEnabled(annotationMetadata)) {
        return NO_IMPORTS;
    } else {
        AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader.loadMetadata(this.beanClassLoader);
        AutoConfigurationImportSelector.AutoConfigurationEntry autoConfigurationEntry =
        this.getAutoConfigurationEntry(autoConfigurationMetadata, annotationMetadata);
        return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
    }
}

多くの自動構成クラス(xxxAutoConfiguration)がコンテナーにインポートされます。つまり、このシナリオに必要なすべてのコンポーネントがコンテナーにインポートされ、これらのコンポーネントが構成されます。

画像

自動構成クラスを使用すると、構成インジェクション機能コンポーネントを手動で作成する作業を回避できます。これらの構成クラスをどのように取得しますか?次のメソッドを見てください。

protected AutoConfigurationImportSelector.AutoConfigurationEntry
  getAutoConfigurationEntry(AutoConfigurationMetadata autoConfigurationMetadata, AnnotationMetadata annotationMetadata) {
    if (!this.isEnabled(annotationMetadata)) {
        return EMPTY_ENTRY;
    } else {
        AnnotationAttributes attributes = this.getAttributes(annotationMetadata);
        List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);
        configurations = this.removeDuplicates(configurations);
        Set<String> exclusions = this.getExclusions(annotationMetadata, attributes);
        this.checkExcludedClasses(configurations, exclusions);
        configurations.removeAll(exclusions);
        configurations = this.filter(configurations, autoConfigurationMetadata);
        this.fireAutoConfigurationImportEvents(configurations, exclusions);
        return new AutoConfigurationImportSelector.AutoConfigurationEntry(configurations, exclusions);
    }
}

getCandidateConfigurations()メソッドを見ることができます。その役割は、システムによってロードされたいくつかのクラスを導入することです。それらはどのクラスですか?

protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
    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 static List<String> loadFactoryNames(Class<?> factoryClass, @Nullable ClassLoader classLoader) {
    String factoryClassName = factoryClass.getName();
    return (List)loadSpringFactories(classLoader).getOrDefault(factoryClassName, Collections.emptyList());
}

META-INF / spring.factoriesからリソースを取得し、プロパティを介してリソースをロードします。

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()) {
                    Map.Entry<?, ?> entry = (Map.Entry)var6.next();
                    String factoryClassName = ((String)entry.getKey()).trim();
                    String[] var9 = StringUtils.commaDelimitedListToStringArray((String)entry.getValue());
                    int var10 = var9.length;

                    for(int var11 = 0; var11 < var10; ++var11) {
                        String factoryName = var9[var11];
                        result.add(factoryClassName, factoryName.trim());
                    }
                }
            }

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

SpringBootは、起動時にクラスパスの下のMETA-INF / spring.factoriesからEnableAutoConfigurationで指定された値を取得し、これらの値を自動構成クラスおよび自動構成クラスとしてコンテナーにインポートすることがわかります。有効になり、自動構成作業を支援します。自分で構成する必要がある前に、自動構成クラスがそれを行ってくれます。次の図に示すように、Springのいくつかの一般的なクラスが自動的にインポートされていることがわかります。

画像

次に、@ ComponentScanアノテーション、@ ComponentScan(excludeFilters = {@Filter(type = FilterType.CUSTOM、classes = TypeExcludeFilter.class)、@ Filter(type = FilterType.CUSTOM、classes = AutoConfigurationExcludeFilter.class)})、このアノテーションを見てください。パッケージをスキャンして、スプリングコンテナに入れます。

@ComponentScan(excludeFilters = {
  @Filter(type = FilterType.CUSTOM,classes = {TypeExcludeFilter.class}),
  @Filter(type = FilterType.CUSTOM,classes = {AutoConfigurationExcludeFilter.class})})
public @interface SpringBootApplication {}

@SpringbootApplicationの要約:言い換えれば、彼は多くのものを準備しており、それを使用するかどうかは、プログラムまたは構成によって異なります。

次に、runメソッドを引き続き確認します。

public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

runメソッドの実行で使用される自動構成が存在するかどうかを確認するには、実行をクリックしてみましょう。

public ConfigurableApplicationContext run(String... args) {
    //计时器
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    ConfigurableApplicationContext context = null;
    Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList();
    this.configureHeadlessProperty();
    //监听器
    SpringApplicationRunListeners listeners = this.getRunListeners(args);
    listeners.starting();

    Collection exceptionReporters;
    try {
        ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
        ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);
        this.configureIgnoreBeanInfo(environment);
        Banner printedBanner = this.printBanner(environment);
        //准备上下文
        context = this.createApplicationContext();
        exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class,
                      new Class[]{ConfigurableApplicationContext.class}, context);
        //预刷新context
        this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);
        //刷新context
        this.refreshContext(context);
        //刷新之后的context
        this.afterRefresh(context, applicationArguments);
        stopWatch.stop();
        if (this.logStartupInfo) {
            (new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch);
        }

        listeners.started(context);
        this.callRunners(context, applicationArguments);
    } catch (Throwable var10) {
        this.handleRunFailure(context, var10, exceptionReporters, listeners);
        throw new IllegalStateException(var10);
    }

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

次に、私たちが懸念しているのは、refreshContext(context);リフレッシュコンテキストです。クリックして見てみましょう。

private void refreshContext(ConfigurableApplicationContext context) {
   refresh(context);
   if (this.registerShutdownHook) {
      try {
         context.registerShutdownHook();
      }
      catch (AccessControlException ex) {
         // Not allowed in some environments.
      }
   }
}

引き続きrefresh(context)をクリックします。

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

彼は((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();
      }
   }
}

春の豆の積み込み工程であることがわかります。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);
   }
}

Webコンテナを作成するcreateWebServer();メソッドがあり、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);
}

なぜそれがインターフェースなのかがわかります。私たちはTomcatWebコンテナ以上のものだからです。

画像

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を作成するプロセスを確認できます。

あなたが理解していない場合、私たちは理解するために別の方法を使用しています、誰もがいくつかの例を与えるためにステータスを知っている必要があります。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

まず、ステータスをカスタマイズします。

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.4.RELEASE</version>
    <relativePath/>
</parent>
<groupId>com.zgw</groupId>
<artifactId>gw-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-autoconfigure</artifactId>
    </dependency>
</dependencies>

まず、Maven構成に記述されているバージョン番号を見てみましょう。ステータス管理者をカスタマイズする場合は、spring-boot-autoconfigureパッケージに依存する必要があります。最初にプロジェクトディレクトリを見てみましょう。

画像

public class GwServiceImpl  implements GwService{
    @Autowired
    GwProperties properties;

    @Override
    public void Hello()
    {
        String name=properties.getName();
        System.out.println(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のステータス管理者はこのように記述されているため、自動構成の目的を達成するためにステータス作成者を模倣するように彼を参照できます。その後、Springを通じて構成します。工場。

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

次に、このような単純なステータス作成者が完成し、Mavenにパッケージ化して、他のプロジェクトで使用できるようになります。

おすすめ

転載: blog.csdn.net/weixin_42073629/article/details/115038578