SpringBoot-@Enable*注解的工作原理
这也就是为什么SpringBoot能够做到零配置的原因所在:
@Enable:启用一些特征来帮我们做一些事情。
写一个实例:写一个线程
package com.boot.enable.bootenable;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
@Component
public class RunnableDemo implements Runnable {
@Override
public void run() {
for(int i=0;i<10;i++){
System.out.println("-----------"+(i+1));
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
主函数如下:
package com.boot.enable.bootenable;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.scheduling.annotation.EnableAsync;
@SpringBootApplication
public class BootEnableApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context =
SpringApplication.run(BootEnableApplication.class, args);
Runnable contextBean = context.getBean(Runnable.class);
System.out.println("---------------start----------------");
contextBean.run();
System.out.println("---------------close----------------");
context.close();
}
}
运行的结果如下:这时执行的效果就是一个同步的,顺序执行的。
然而在springBoot中可以启用异步的方式来让我们的方法去异步的去执行:
1,在方法上加上注解:@Async,如果这个方法被异步的去执行的话:
这个注解:它用的是并发编程的juc下的executor。
和spring的TaskExecutor:异步编程的模型来做的。
package org.springframework.scheduling.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Async {
String value() default "";
}
2,然后在主类上去启用这个异步的特征:告诉她要启用异步的方式去配置
@EnableAsync
package com.boot.enable.bootenable;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.scheduling.annotation.EnableAsync;
@SpringBootApplication
@EnableAsync
public class BootEnableApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context =
SpringApplication.run(BootEnableApplication.class, args);
Runnable contextBean = context.getBean(Runnable.class);
System.out.println("---------------start----------------");
contextBean.run();
System.out.println("---------------close----------------");
context.close();
}
}
运行的结果如下:这时就是异步的操作了,主线程执行完了,异步的线程还在执行。
总结:原来没有学习springBoot的时候在写一个异步操作的话必须用到callable和FeauterTasker才能够做到。而学习了springBoot的话两步操作就可以了:1,在方法上标注为异步的方法的注解 . 2, 在主方法上启用异步的注解。
原理如下:
@EnableAsync=@Import({AsyncConfigurationSelector.class})
最主要的作用是这个@Import的注解:
源代码如下:
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package org.springframework.scheduling.annotation;
import java.lang.annotation.Annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.context.annotation.AdviceMode;
import org.springframework.context.annotation.Import;
@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 2147483647;
}
AsyncConfigurationSelector这个类继承了AdviceModeImportSelector<EnableAsync>
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package org.springframework.scheduling.annotation;
import org.springframework.context.annotation.AdviceMode;
import org.springframework.context.annotation.AdviceModeImportSelector;
import org.springframework.lang.Nullable;
public class AsyncConfigurationSelector extends AdviceModeImportSelector<EnableAsync> {
private static final String ASYNC_EXECUTION_ASPECT_CONFIGURATION_CLASS_NAME = "org.springframework.scheduling.aspectj.AspectJAsyncConfiguration";
public AsyncConfigurationSelector() {
}
@Nullable
public String[] selectImports(AdviceMode adviceMode) {
switch(adviceMode) {
case PROXY:
return new String[]{ProxyAsyncConfiguration.class.getName()};
case ASPECTJ:
return new String[]{"org.springframework.scheduling.aspectj.AspectJAsyncConfiguration"};
default:
return null;
}
}
}
然后这个类AdviceModeImportSelector实现了
ImportSelector这个接口,从而去判断是哪种类型,如果是代理的话,就返回代理对象的数组,如果是切面的话,就返回切面的数组的实例到spring容器中。
在这个类里面异步回调的处理器 AsyncAnnotationBeanPostProcessor。在这里就会开启一个线程对象去执行上面的方法。
public class ProxyAsyncConfiguration extends AbstractAsyncConfiguration {
public ProxyAsyncConfiguration() {
}
@Bean(
name = {"org.springframework.context.annotation.internalAsyncAnnotationProcessor"}
)
@Role(2)
public AsyncAnnotationBeanPostProcessor asyncAdvisor() {
Assert.notNull(this.enableAsync, "@EnableAsync annotation metadata was not injected");
AsyncAnnotationBeanPostProcessor bpp = new AsyncAnnotationBeanPostProcessor();
Class<? extends Annotation> customAsyncAnnotation = this.enableAsync.getClass("annotation");
if (customAsyncAnnotation != AnnotationUtils.getDefaultValue(EnableAsync.class, "annotation")) {
bpp.setAsyncAnnotationType(customAsyncAnnotation);
}
if (this.executor != null) {
bpp.setExecutor(this.executor);
}
if (this.exceptionHandler != null) {
bpp.setExceptionHandler(this.exceptionHandler);
}
bpp.setProxyTargetClass(this.enableAsync.getBoolean("proxyTargetClass"));
bpp.setOrder((Integer)this.enableAsync.getNumber("order"));
return bpp;
}
}
总结:@Enable*的特性就是依赖于@Impor这个这个特性。springBoot的入门(四)写到@Import注解的特性。