pring boot Starterと自動配置

19493 ワード

例えば、spring-cloud-starter-feignのようなmaven依存や@EnbaleMongo注解などがよく見られます.直接に関連するbeanオブジェクトを使って機能を実現します.これらはどうやって作ったのですか?どのような方法で作ったのですか?今日は暇があれば整理してください.
ここはまだ一つの方法のまとめですから、原理解釈はやはり参考資料を見なければなりません.
私は3つの方法をまとめました.3つの方法には共通点があります.前に言ってください.後の文は対照的に理解できます.
  • の3つの方法の重点基礎はすべてImport注釈であり、この注釈は自動配置の基礎
  • である.
  • すべての自動ローディングプロファイルのクラスは、@Configration注釈の修飾が必要な
  • です.
  • すべての自動ローディングプロファイルのクラスは@EnbaleConfigrationPropertiesを使用して属性ファイルをロードし、Codition関連の注釈によってローディングの条件を設定します.具体的には方法3
  • を参照してください.
    方法1:Spring BootationまたはEnbaleAutoConfigrationを使用します.この注釈はすべてのJARカバンの中のspring.factoresファイルをスキャンして、EnbaleAutoConfigration属性に配置されたクラスをロードします.
    したがって、私たちは注釈を使って、spring.factoresにロードするクラスの全パス名を定義するだけです.例えば、spring-boot-at configreというmaven依存の中のspring.factoresファイルは、ここでの\は、改行後に属性を読み取るために、複数の種類が使用され、分離されています.
    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,\
    org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\
    org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\
    
    この方法はあなたに適しています.比較的完備していて、複雑で、多くの機能モジュールに依存しています.
    このような方式の原理は簡単に説明されています.@Importを使ってEnbaleAutoConfigrationImportSelector類をロードし、その親類AutoConfigrationImportSelectorでImport Selectorインターフェースを実現しました.
    @SuppressWarnings("deprecation")
    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Inherited
    @AutoConfigurationPackage
    @Import(EnableAutoConfigurationImportSelector.class)
    public @interface EnableAutoConfiguration {
    
    	String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";
    	Class<?>[] exclude() default {};
    	String[] excludeName() default {};
    
    }
    
    Import Selector萼selectImportsはどのクラスにロードされる必要がありますか?
    public interface DeferredImportSelector extends ImportSelector {
    
    }
    
    public interface ImportSelector {
    
    	/**
    	 * Select and return the names of which class(es) should be imported based on
    	 * the {@link AnnotationMetadata} of the importing @{@link Configuration} class.
    	 */
    	String[] selectImports(AnnotationMetadata importingClassMetadata);
    
    }
    
    AutoConfigrationImports Selector(zhi selectImports)では、spring.factoresファイルをここにロードするために、指定された属性のEnbaleAutoConfigrationを読み込む方法を呼び出します.
    protected List<String> getCandidateConfigurations(AnnotationMetadata metadata,
    			AnnotationAttributes attributes) {
    		List<String> configurations = SpringFactoriesLoader.loadFactoryNames(
    				getSpringFactoriesLoaderFactoryClass(), 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;
    	}
    
    方法の2つの方法は、実際には方法から進化したものであり、方法の1つの本質は、ImportSelectorインターフェースを実現することによって、自動的に入り混じっているクラスの全パス名を返すことである.だから、Import Selectorインターフェースを実現するクラスをカスタマイズすることができる.
    例えば、spring-contextの@EnbaleCaching注釈は、まずImportでCachingConfigrationSelector類をロードする.CachingConfigrationSelector類はImport Selectorインターフェースを実現し、selectImports方法でクラス全パス名を返しました.
    方法の2と方法は同じで、あなたに適しています.比較的に完備していて、複雑で、多くの機能モジュールに依存しています.
    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Import(CachingConfigurationSelector.class)
    public @interface EnableCaching {
    	boolean proxyTargetClass() default false;
    	AdviceMode mode() default AdviceMode.PROXY;
    	int order() default Ordered.LOWEST_PRECEDENCE;
    
    }
    
    @Override
    	public String[] selectImports(AdviceMode adviceMode) {
    		switch (adviceMode) {
    			case PROXY:
    				return getProxyImports();
    			case ASPECTJ:
    				return getAspectJImports();
    			default:
    				return null;
    		}
    	}
    
    方法3:この方法は単に@Configrationによって注釈された修飾されたクラスをロードします.例えば@EnbaleMongo注釈はImportによって注釈され、Mongo AutoConfigration類をロードします.
    これらのBeanオブジェクトは構成ファイルに依存しています.構成ファイルは@EnbaleConfigrationPropertiesで定義されています.設定ファイルでは@ConfigrationProptiesの注釈で構成属性のソースを定義します.
    @Documented
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.TYPE})
    @Import({MongoAutoConfiguration.class})
    public @interface EnableMongo {
    }
    
    @Configuration
    @EnableConfigurationProperties({MongoProperties.class})
    public class MongoAutoConfiguration {
        @Autowired
        private MongoProperties mongoProperties;
    
        public MongoAutoConfiguration() {
        }
    
        @Bean
        public MongoClient mongo() {
            ……
        }
    
        @Bean
        public DB mongoDB(MongoClient mongo) {
    		……
        }
    
        @Bean
        public MongoManager mongoManager(DB mongoDB) {
            return new MongoManager(mongoDB);
        }
    }
    
    @ConfigurationProperties(
        prefix = "mongo"
    )
    public class MongoProperties 
    
    この他にもorg.springframe work.boot.aut configre.com nditionの条件によってカスタマイズできます.どのような条件で異なるクラスをロードしますか?
    @Configuration
    	@ConditionalOnClass({ HystrixCommand.class, HystrixFeign.class })
    	protected static class HystrixFeignConfiguration {
    		@Bean
    		@Scope("prototype")
    		@ConditionalOnMissingBean
    		@ConditionalOnProperty(name = "feign.hystrix.enabled", matchIfMissing = false)
    		public Feign.Builder feignHystrixBuilder() {
    			return HystrixFeign.builder();
    		}
    	}
    
    条件コメントは以下の通りです
    注釈
    説明
    @Conditional OnBen
    容器に指定されたビーンがある場合.
    @Contintional Onclass
    クラスパスの下に指定されたクラスがある場合.
    @Conditional OnExpression
    SpEL式に基づいて判定条件とします.
    @Conditional OnJava
    JVMバージョンに基づいて判断条件とします.
    @Condtional OnJdi
    JNDIが存在する条件で指定された位置を検索します.
    @Conditional OnMissingBen
    容器にビーンが指定されていない場合.
    @Contintional OnMissingClass
    クラスパスに指定されたクラスがない場合.
    @Coditional OnNotWebAppleication
    現在のプロジェクトはWebプロジェクトの条件ではない.
    @Comptional OnProperty
    指定された属性に指定された値があるかどうか.
    @Conditional OnResource
    クラスパスに指定された値があるかどうか.
    @Condtional OnSingleCanddidate
    ビーンを指定する場合は、コンテナの中に一つしかない場合や、複数ありますが、優先するビーンを指定します.
    @Coditional OnWebApplication
    現在のプロジェクトはWebプロジェクトの条件のもとです.