@ enable *アノテーション
SpringBootの自動構成の原則を分析すると、これらの@ Enable *アノテーションのソースコードを観察でき、すべてのアノテーションに@Importアノテーションがあることがわかります。@Importアノテーションは、構成クラスをインポートするために使用されます。つまり、これらの自動オープン実装は、実際にはいくつかの自動構成Beanをインポートします。
例:FreeMarkerの自動構成クラスFreeMarkerAutoConfiguration、この自動構成クラスでは、クラスローダー内のいくつかのクラスが存在し、他のいくつかの構成クラスの後にロードされる必要があります。
ただし、一部の注釈スイッチが使用されている場合にのみ有効になる自動構成クラスもいくつかあります。たとえば、spring-boot-starter-batchの@EnableBatchProcessingアノテーションと@EnableCaching。
1.自動インジェクションの例
アノテーションを定義します。EnableContentServiceを使用すると、このアノテーションを使用するクラスで、いくつかのクラスをインジェクトしたり、いくつかの低レベルの処理を実行したりできます。
Springが提供する@Importアノテーションを構成クラスとともに使用して完了します。
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Import(ContentConfiguration.class)
public @interface EnableContentService {
}
public interface ContentService {
void doSomething();
}
public class SimpleContentService implements ContentService {
@Override
public void doSomething() {
System.out.println("do some simple things");
}
}
次に、@ EnableContentServiceアノテーションをアプリケーションのエントリに追加します。
この場合、ContentServiceが注入されます。SpringBootもこれで行われます。より高度なImportSelectorを使用するだけです。
@Importの使用方法。
最初のカテゴリ:構成クラスを直接インポートします。
たとえば、@ EnableSchedulingは構成クラスSchedulingConfigurationを直接インポートし、このクラスには@Configurationアノテーションが付けられ、scheduledAnnotationProcessorのBeanが登録されます。
@Target({
ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Import({
SchedulingConfiguration.class})
@Documented
public @interface EnableScheduling {
}
2番目のタイプ:条件に従って構成クラスを選択します。
たとえば、@ EnableAsyncでは、構成クラスの構成はAsyncConfigurationSelector.classによって選択されます。
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(AsyncConfigurationSelector.class)
public @interface EnableAsync {
Class<? extends Annotation> annotation() default Annotation.class;
boolean proxyTargetClass() default false;
AdviceMode mode() default AdviceMode.PROXY;
int order() default Ordered.LOWEST_PRECEDENCE;
}
AsyncConfigurationSelectorは、条件を介してインポートする必要のある構成クラスを選択します。AsyncConfigurationSelectorのルートインターフェイスはImportSelectorです。このインターフェイスは、selectImportsメソッドを書き直して、このメソッドで前提条件を判断する必要があります。
AdviceModeがPORXYの場合、構成クラスProxyAsyncConfigurationが返されます。
activeModeがASPECTJの場合、AspectJAsyncConfiguration構成クラスが返されます。
主な方法は次のとおりです。
public class AsyncConfigurationSelector extends AdviceModeImportSelector<EnableAsync> {
private static final String ASYNC_EXECUTION_ASPECT_CONFIGURATION_CLASS_NAME =
"org.springframework.scheduling.aspectj.AspectJAsyncConfiguration";
/**
* {@inheritDoc}
* @return {@link ProxyAsyncConfiguration} or {@code AspectJAsyncConfiguration} for
* {@code PROXY} and {@code ASPECTJ} values of {@link EnableAsync#mode()}, respectively
*/
@Override
public String[] selectImports(AdviceMode adviceMode) {
switch (adviceMode) {
case PROXY:
return new String[] {
ProxyAsyncConfiguration.class.getName() };
case ASPECTJ:
return new String[] {
ASYNC_EXECUTION_ASPECT_CONFIGURATION_CLASS_NAME };
default:
return null;
}
}
}
3番目のカテゴリ:
BeanSpringでのEnableAspectJAutoProxy.javaの動的登録
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(AspectJAutoProxyRegistrar.class)
public @interface EnableAspectJAutoProxy {
boolean proxyTargetClass() default false;
boolean exposeProxy() default false;
}
AspectJAutoProxyRegistrarは、ImportBeanDefinitionRegistrarインターフェースを実装します。ImportBeanDefinitionRegistrarの役割は、メソッドを書き直すことにより、実行時に既存の構成クラスにBeanを自動的に追加することです。
class AspectJAutoProxyRegistrar implements ImportBeanDefinitionRegistrar {
/**
* Register, escalate, and configure the AspectJ auto proxy creator based on the value
* of the @{@link EnableAspectJAutoProxy#proxyTargetClass()} attribute on the importing
* {@code @Configuration} class.
*/
@Override
public void registerBeanDefinitions(
AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry);
AnnotationAttributes enableAspectJAutoProxy =
AnnotationConfigUtils.attributesFor(importingClassMetadata, EnableAspectJAutoProxy.class);
if (enableAspectJAutoProxy.getBoolean("proxyTargetClass")) {
AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
}
if (enableAspectJAutoProxy.getBoolean("exposeProxy")) {
AopConfigUtils.forceAutoProxyCreatorToExposeProxy(registry);
}
}
}
その中で、AnnotationMetadataパラメーターは、現在の構成クラスの注釈を取得するために使用されます。
BeanDefinittionRegistryパラメーターは、Beanを登録するために使用されます。
SpringBootでのImportSelectorの使用SpringBootでのImportSelectorは、SpringBoot
によって提供されるアノテーション@EnableAutoConfigurationを介して完了します。
この@EnableAutoConfigurationアノテーションは明示的に呼び出すことができます。そうでない場合は、@ SpringBootApplicationアノテーションで暗黙的に呼び出されます。
@EnableAutoConfigurationアノテーションは、EnableAutoConfigurationImportSelectorをImportSelectorとして使用します。次のコードは、EnableAutoConfigurationImportSelectorで選択するための特定のコードです。
@Override
public String[] selectImports(AnnotationMetadata metadata) {
try {
AnnotationAttributes attributes = getAttributes(metadata);
List<String> configurations = getCandidateConfigurations(metadata,
attributes);
configurations = removeDuplicates(configurations); // 删除重复的配置
Set<String> exclusions = getExclusions(metadata, attributes); // 去掉需要exclude的配置
configurations.removeAll(exclusions);
configurations = sort(configurations); // 排序
recordWithConditionEvaluationReport(configurations, exclusions);
return configurations.toArray(new String[configurations.size()]);
}
catch (IOException ex) {
throw new IllegalStateException(ex);
}
}
getCandidateConfigurationsメソッドは、構成クラスを取得します。
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata,
AnnotationAttributes attributes) {
return SpringFactoriesLoader.loadFactoryNames(
getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader());
}
SpringFactoriesLoader.loadFactoryNamesメソッドは、静的変数FACTORIES_RESOURCE_LOCATIONに従って、すべてのjarパッケージからMETA-INF /spring.factoriesファイル情報を読み取ります。
public static List<String> loadFactoryNames(Class<?> factoryClass, ClassLoader classLoader) {
String factoryClassName = factoryClass.getName();
try {
Enumeration<URL> urls = (classLoader != null ? classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
List<String> result = new ArrayList<String>();
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
Properties properties = PropertiesLoaderUtils.loadProperties(new UrlResource(url));
String factoryClassNames = properties.getProperty(factoryClassName); // 只会过滤出key为factoryClassNames的值
result.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(factoryClassNames)));
}
return result;
}
catch (IOException ex) {
throw new IllegalArgumentException("Unable to load [" + factoryClass.getName() +
"] factories from location [" + FACTORIES_RESOURCE_LOCATION + "]", ex);
}
}
getCandidateConfigurationsメソッドのgetSpringFactoriesLoaderFactoryClassメソッドはEnableAutoConfiguration.classを返すため、キーの値をorg.springframework.boot.autoconfigure.EnableAutoConfigurationとして除外します。
次の構成コードは、autoconfigure jarパッケージのspring.factoriesファイルの一部です(org.springframework.boot.autoconfigure.EnableAutoConfigurationのキーがあるため、これらのAutoConfigurationsを取得します)。
# Initializers
org.springframework.context.ApplicationContextInitializer=\
org.springframework.boot.autoconfigure.logging.AutoConfigurationReportLoggingInitializer
# Application Listeners
org.springframework.context.ApplicationListener=\
org.springframework.boot.autoconfigure.BackgroundPreinitializer
# 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.MessageSourceAutoConfiguration,\......
もちろん、これらのAutoConfigurationのすべてがロードされるわけではありません。AutoConfigurationの@ConditionalOnClassなどの条件に従ってロードするかどうかが決定されます。
上記の例では、プロパティファイルを読み取るときに、キーがorg.springframework.boot.autoconfigure.EnableAutoConfigurationである値のみが除外されます。
SpringBoot内には、ロードする必要のあるクラスをフィルタリングするために使用される他のいくつかのキーがあります。
org.springframework.test.context.TestExecutionListener
org.springframework.beans.BeanInfoFactory
org.springframework.context.ApplicationContextInitializer
org.springframework.context.ApplicationListener
org.springframework.boot.SpringApplicationRunListener
org.springframework.boot.env.EnvironmentPostProcessor
org.springframework.boot.env.PropertySourceLoader
@ Enable *春に
@EnableAspectJAutoProxy
@EnableAspectJAutoProxyアノテーションは、アスペクト自動プロキシをアクティブにします。@ EnableAspectJAutoProxyを使用すると、AspectJ自動プロキシサポートを有効にする<aop:aspectj-autoproxy />と同等です。
@EnableAsync
@EnableAsyncアノテーションは、非同期メソッドのサポートを有効にします。
リンクの説明を追加するには、「@ Async非同期呼び出しの実装」を参照してください。
@EnableScheduling
@EnableSchedulingアノテーションは、スケジュールされたタスクのサポートを有効にします。
リンクの説明を追加するには、「Springの@Scheduled TaskScheduling」を参照してください。
@EnableWebMVC
@EnableWebMVCアノテーションは、WebMVC構成サポートを有効にするために使用されます。
SpringMVCを作成するときに使用されます。
@EnableConfigurationProperties
@EnableConfigurationPropertiesアノテーションは、@ ConfigurationPropertiesアノテーション構成Beanのサポートを有効にするために使用されます。
@EnableJpaRepositories
@EnableJpaRepositoriesアノテーションは、Spring Data JPARepostoryのサポートを有効にします。
Spring Data JPAフレームワークは、主にSpringが簡略化していない唯一のビジネスロジックコードを対象としています。これまでのところ、開発者は永続層のビジネスロジックを実装するための残りの作業を保存しています。唯一のことは、のインターフェイスを宣言することです。永続性レイヤー。、そしてSpring Data JPAが残りを行います!
簡単に言えば、Spring DataJPAはデータを永続化するためのフレームワークです。
@EnableTransactionManagement
@EnableTransactionManagementアノテーションは、アノテーション付きトランザクションのサポートを有効にします。
アノテーション@EnableTransactionManagementは、@ Transactionalアノテーション付きクラスがトランザクションの側面に囲まれていることをSpringに通知します。次に、@ Transactionalを使用できます。
@EnableCaching
@EnableCachingアノテーションは、アノテーションスタイルのキャッシングサポートを有効にします