SpringBoot(アノテーション)

1.メインクラスの注釈を分析します

import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan(basePackages = "com.wangxing.springboot")
public class Springbootdemo1Application {
    
    
    public static void main(String[] args) {
    
    
  	SpringApplication.run(Springbootdemo1Application.class, args);
    }
}

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

1. @SpringBootApplicationは、実際には複合アノテーションです。
その定義では複数のアノテーションが使用されていますが、実際、SpringBootアプリケーションの場合、重要なアノテーションは3つだけで、次の3つです。

@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {@Filter(type = FilterType.CUSTOM、classes = TypeExcludeFilter.class)、
@ Filter(type = FilterType.CUSTOM、classes = AutoConfigurationExcludeFilter.class)})

したがって、メインクラスで上記の3つのアノテーションを使用する場合でも、SpringBootアプリケーション全体は以前のスタートアップクラスと機能的に同等である可能性があります。

package com.wangxing.springboot.springbootdemo2;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigurationExcludeFilter;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.TypeExcludeFilter;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
    
     @ComponentScan.Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
        @ComponentScan.Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public class Springbootdemo2Application {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(Springbootdemo2Application.class, args);
    }
}

ただし、毎回3つのアノテーションを作成するのは明らかに面倒なので、@ SpringBootApplicationのようなワンストップの複合アノテーションを作成する方が明らかに便利です。
@SpringBootConfigurationアノテーション[構成ファイルを置き換える構成クラスを作成する]
@SpringBootConfigurationアノテーションには@Configurationが含まれます。
@Configuration – SpringJavaConfigの形式でSpringIoCコンテナーの構成クラスによって使用されるアノテーションです。SpringBootアプリケーションは本質的にSpringアプリケーションであるため、特定のIoCコンテナーの構成をロードする必要があり、SpringBootコミュニティはJavaConfigベースの構成フォームの使用を推奨しています。したがって、スタートアップクラスがここでは@Configurationアノテーションが付けられています。これは、IoCコンテナーの構成クラスでもあります。構成方法
スプリングJavaConfigの形態におけるスプリングIoCコンテナの1 XMLベースの設定方法。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
<!-- bean定义 -->

</beans>

2.JavaConfigに基づく構成方法

@Configuration
public class MyConfiguration{
// bean定义
} 

@ConfigurationでマークされたJavaクラス定義は、JavaConfig構成クラスです。
登録Beanの定義
1.XMLベースの登録Beanの定義方法。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
<!-- bean定义 -->
<bean id=””  class=””></bean>
</beans>

2.JavaConfigに基づく登録済みBean定義メソッド。

@Configuration
public class MyConfiguration{
    
    
// bean定义
 	@Bean
    public StudentService  studentService() {
    
    
        return new StudentServiceImpl();
    }
} 

@Beanアノテーションが付けられたメソッドの場合、その戻り値はSpringのIoCコンテナーにBean定義として登録され、メソッド名はデフォルトでBean定義のIDになります。依存性注入の
構成方法
1.XMLベースの依存性注入方法

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
<!-- bean定义 -->
<bean id=””  class=””>
<property name="studentDao" ref="studentDao" />
</bean>
</beans>

2.JavaConfigに基づく依存性注入方法。

@Configuration
public class MyConfiguration{
    
    
// bean定义
 	@Bean
    public StudentService  studentService() {
    
    
        return new StudentServiceImpl(studentDao() );
}

	@Bean
    public  StudentDao  studentDao() {
    
    
        return new StudentDaoImpl();
	}
} 

Beanの定義が他のBeanに依存している場合は、対応するJavaConfigクラスの依存Beanの作成メソッドを直接呼び出すだけです。

@SpringBootApplicationには@SpringBootConfigurationアノテーションが含まれ、@ SpringBootConfigurationアノテーションには@Configurationアノテーションが含まれ、@ ConfigurationアノテーションがマークされているJavaクラス、このJavaクラスはJavaConfig構成クラス、このJavaConfig構成クラスはSpring構成ファイル[ApplicationContext.xml ]、メインクラスで@SpringBootApplicationにアノテーションを付けると、メインクラスがJavaConfig構成クラスであることを意味するため、SptingBootプロジェクトを作成するときにSpring構成ファイル[applicationContext.xml]を記述する必要はありません。

@EnableAutoConfiguration ["スマート"完全自動構成]
1。@ EnableAutoConfigurationには
、JavaConfig構成クラスにBeanオブジェクトを登録するための@Importアノテーション@Importアノテーションが含まれています。
@EnableAutoConfigurationアノテーションは、@ Importアノテーションを使用して、特定のモジュールに関連するBean定義を収集および登録します。
ソースコード:

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

@Import(AutoConfigurationImportSelector.class)。@ EnableAutoConfigurationは、EnableAutoConfigurationImportSelectorを使用して、SpringBootアプリケーションがすべての適格な@Configuration構成をSpringBootによって作成および使用される現在のIoCコンテナーにロードするのに役立ちます。
ここに画像の説明を挿入

Springフレームワークの元のツールクラスであるSpringFactoriesLoaderのサポートにより、@ EnableAutoConfigurationは、関数を「インテリジェントに」正常に構成することができます。

** @ Import(AutoConfigurationImportSelector.class)**のAutoConfigurationImportSelector.class内

protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
   List<String> configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(),
         getBeanClassLoader());
   Assert.notEmpty(configurations, "No auto configuration classes found in METAINF/spring.factories. If you "+ "are using a custom packaging, make sure that file is correct.");
   return configurations;
}

SpringFactoriesLoaderクラス

public static <T> List<T> loadFactories(Class<T> factoryType, @Nullable ClassLoader classLoader) {
    
    
   Assert.notNull(factoryType, "'factoryType' must not be null");
   ClassLoader classLoaderToUse = classLoader;
   if (classLoaderToUse == null) {
    
    
      classLoaderToUse = SpringFactoriesLoader.class.getClassLoader();
   }
   List<String> factoryImplementationNames = loadFactoryNames(factoryType, classLoaderToUse);
   if (logger.isTraceEnabled()) {
    
    
      logger.trace("Loaded [" + factoryType.getName() + "] names: " + factoryImplementationNames);
   }
   List<T> result = new ArrayList<>(factoryImplementationNames.size());
   for (String factoryImplementationName : factoryImplementationNames) {
    
    
      result.add(instantiateFactory(factoryImplementationName, factoryType, classLoaderToUse));
   }
   AnnotationAwareOrderComparator.sort(result);
   return result;
}
public static List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) {
    
    
   ClassLoader classLoaderToUse = classLoader;
   if (classLoaderToUse == null) {
    
    
      classLoaderToUse = SpringFactoriesLoader.class.getClassLoader();
   }
   String factoryTypeName = factoryType.getName();
   return loadSpringFactories(classLoaderToUse).getOrDefault(factoryTypeName, Collections.emptyList());
}

private static Map<String, List<String>> loadSpringFactories(ClassLoader classLoader) {
    
    
   Map<String, List<String>> result = cache.get(classLoader);
   if (result != null) {
    
    
      return result;
   }

   result = new HashMap<>();
   try {
    
    
      Enumeration<URL> urls = classLoader.getResources(FACTORIES_RESOURCE_LOCATION);
      while (urls.hasMoreElements()) {
    
    
         URL url = urls.nextElement();
         UrlResource resource = new UrlResource(url);
         Properties properties = PropertiesLoaderUtils.loadProperties(resource);
         for (Map.Entry<?, ?> entry : properties.entrySet()) {
    
    
            String factoryTypeName = ((String) entry.getKey()).trim();
            String[] factoryImplementationNames =
                  StringUtils.commaDelimitedListToStringArray((String) entry.getValue());
            for (String factoryImplementationName : factoryImplementationNames) {
    
    
               result.computeIfAbsent(factoryTypeName, key -> new ArrayList<>())
                     .add(factoryImplementationName.trim());
            }
         }
      }
      // Replace all lists with unmodifiable lists containing unique elements
      result.replaceAll((factoryType, implementations) -> implementations.stream().distinct()
            .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)));
      cache.put(classLoader, result);
   }
   catch (IOException ex) {
    
    
      throw new IllegalArgumentException("Unable to load factories from location [" +
            FACTORIES_RESOURCE_LOCATION + "]", ex);
   }
   return result;
}


public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";
spring-boot-autoconfigure-2.4.0.jar/META-INF/spring.factories
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
...........

SpringBootコア自動構成の原則
1)SpringBootが起動すると、メイン構成クラスがロードされ、自動構成機能がオンになります。@ EnableAutoConfiguration
メインクラスは@SpringBootConfigurationアノテーションを追加し、@ SpringBootConfigurationアノテーションは@EnableAutoConfigurationアノテーションを含みます
2)。@ EnableAutoConfigurationアノテーション使用@import(AutoConfigurationImportSelector.classのパラメータEnableAutoConfigurationImporttSelector)輸入いくつかの構成要素
SpringIOCの容器;(annotationMetadata)AutoConfigurationEntry autoConfigurationEntry = getAutoConfigurationEntryを見つけ、見つけ
getAutoConfigurationEntry( メソッドは、一覧の構成= getCandidate構成= getCandidate属性);
getCandidateConfigurations()に
リスト構成の取得= SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass()、
getBeanClassLoader()); SpringFactoriesLoaderクラスを取得し、SpringFactoriesLoaderクラスのloadFactoryNamesメソッドを介してloadSpringFactories()を見つけます。文がありますProperties properties = PropertiesLoaderUtils.loadProperties(resource);
get public static final String FACTORIES_RESOURCE_LOCATION = "META-INF / spring。 "factories";
すべてのjarパッケージクラスパスをスキャンします。META-INF/ spring.factories
は、スキャンされたこれらのファイルのコンテンツをプロパティオブジェクト
パッケージ化して、プロパティからEnableAutoConfiguration.classクラス(クラス名)に対応する値を取得します。次に、それらをコンテナーに追加し、META-INF / spring.factoriesで構成されたEnableAutoConfigurationのすべての値をコンテナーへのクラスパスの下に追加します
3)。各自動構成クラスは自動構成機能を実行します;
4)。さまざまな現在の状況に応じて判断し、この構成クラスを有効にするかどうかを決定しますか?構成クラスが有効になると、この構成はクラスコンテナのさまざまなコンポーネントに追加されます。コンポーネントのこれらのプロパティは、クラスの対応するプロパティから取得されます。これらの各クラスのプロパティはバインディングとプロファイルです
。HttpEncodingAutoConfiguration(Httpエンコーディング自動構成)は、自動構成の原理を説明する例です
。//これは構成クラスであることを意味します。以前に作成した構成ファイルと同じではなく、コンポーネントをコンテナーに追加することもできます。

@Configuration(proxyBeanMethods = false)
//启动指定类的ConfigurationProperties功能,将配置文件中对应的值和HttpEncodingAutoConfigurationProperties绑定起来;
@EnableConfigurationProperties(ServerProperties.class)
//Spring底层@Conditional注解,根据不同的条件,如果满足指定的条件,整个配置类里面的配置就会生效(即判断当前应用是否是web应用)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
//判断当前项目有没有这个类CharacterEncodingFilter;SpringMVC中进行乱码处理的过滤器
@ConditionalOnClass(CharacterEncodingFilter.class)
@ConditionalOnProperty(prefix = "server.servlet.encoding", value = "enabled", matchIfMissing = true)
public class HttpEncodingAutoConfiguration {

   private final Encoding properties;

   public HttpEncodingAutoConfiguration(ServerProperties properties) {
      this.properties = properties.getServlet().getEncoding();
   }

   @Bean
   @ConditionalOnMissingBean
   public CharacterEncodingFilter characterEncodingFilter() {
      CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
      filter.setEncoding(this.properties.getCharset().name());
      filter.setForceRequestEncoding(this.properties.shouldForce(Encoding.Type.REQUEST));
      filter.setForceResponseEncoding(this.properties.shouldForce(Encoding.Type.RESPONSE));
      return filter;
   }

   @Bean
   public LocaleCharsetMappingsCustomizer localeCharsetMappingsCustomizer() {
      return new LocaleCharsetMappingsCustomizer(this.properties);
   }

   static class LocaleCharsetMappingsCustomizer
         implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>, Ordered {

      private final Encoding properties;

      LocaleCharsetMappingsCustomizer(Encoding properties) {
         this.properties = properties;
      }

      @Override
      public void customize(ConfigurableServletWebServerFactory factory) {
         if (this.properties.getMapping() != null) {
            factory.setLocaleCharsetMappings(this.properties.getMapping());
         }
      }

      @Override
      public int getOrder() {
         return 0;
      }
   }
}

5.構成ファイルで構成できるすべてのプロパティは、xxxxPropertitesクラスにカプセル化されます。構成ファイルで構成できるものは、特定の関数に対応するプロパティクラスを参照できます。
@ ComponentScan
[自動スキャンパッケージを構成します。クラスに@Componentと@ Repository、@ Serviceアノテーションを持つjavaクラスがオブジェクトを作成させることができます]
@ComponentScanは、XML構成フォームの<context:component-scan>要素に対応し、次のようないくつかのメタ情報アノテーションと連携するために使用されます。 @Componentや@Repositoryなどとして、これらのメタ情報アノテーションでマークされたBean定義クラスをSpringのIoCコンテナにバッチで収集します。basePackagesなどの属性を使用して、@ ComponentScan自動スキャンのスコープをきめ細かくカスタマイズできます。指定しない場合、デフォルトのSpringフレームワーク実装は@ComponentScanクラスが宣言されているパッケージからスキャンします。
現在のアプリケーションに、@ ComponentScanを介して現在のSpringBootアプリケーションで使用されるIoCコンテナにロードする必要のあるBean定義がない場合、@ ComponentScan宣言を削除しても、現在のSpringBootアプリケーションは同等の関数で通常どおり実行できます。

SpringBoot自動構成
ここに画像の説明を挿入
mybatis-spring-boot-starter、spring-boot-starter-web、およびその他のコンポーネントの主要コンポーネントのMETA-INFファイルには、すべてspring.factoriesファイルが含まれています。自動構成モジュールでは、 SpringFactoriesLoaderによってファイルに収集されたクラスは、クラスのフルネームの配列を返します。返されたクラスのフルネームは、リフレクションによってインスタンス化され、特定のファクトリインスタンスを形成します。ファクトリインスタンスは、コンポーネントが特に必要とするBeanを生成します

おすすめ

転載: blog.csdn.net/guoguo0717/article/details/110622303