Introduction
When using Spring, we only need an Enable annotation to realize the function of opening a module, which is very convenient, so how is this function realized?
Our commonly used Enable annotations are as follows
annotation | effect |
---|---|
@EnableAspectJAutoProxy | Turn on AspectJ automatic proxy |
@EnableAsync | Enable asynchronous method support |
@EnableScheduling | Turn on timer task support |
@EnableWebMVC | Enable web mvc support |
@EnableTransactionManagement | Turn on annotated transaction support |
@EnableCaching | Enable annotation cache support |
@EnableAutoConfiguration | Turn on automatic configuration |
In fact, the bottom layer of the Enable annotation is realized through the @Import annotation, and the @Import annotation will inject the required Bean into the spring container
There are three ways of @Import annotation to inject Beans as follows
- Based on Configuration Class
- Based on ImportSelector interface
- Based on ImportBeanDefinitionRegistrar interface
Demonstrate a wave
@EnableHelloWorld
public class EnableModuleDemo {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(EnableModuleDemo.class);
context.refresh();
String helloWorld = context.getBean("helloWorld", String.class);
// hello world
System.out.println(helloWorld);
context.close();
}
}
You can see that after starting the container, you can get the Bean named helloWorld from the container. The injection process is in the @EnableHelloWorld annotation
Based on Configuration Class
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import(HelloWorldConfiguration.class)
public @interface EnableHelloWorld {
}
@Configuration
public class HelloWorldConfiguration {
@Bean
public String helloWorld() {
return "hello world";
}
}
Based on ImportSelector interface
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import(HelloWorldImportSelector.class)
public @interface EnableHelloWorld {
}
public class HelloWorldImportSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
return new String[]{
"com.javashitang.HelloWorldConfiguration"};
}
}
Based on ImportBeanDefinitionRegistrar interface
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import(HelloWorldImportBeanDefinitionRegistrar.class)
public @interface EnableHelloWorld {
}
public class HelloWorldImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
AnnotatedGenericBeanDefinition beanDefinition = new AnnotatedGenericBeanDefinition(HelloWorldConfiguration.class);
BeanDefinitionReaderUtils.registerWithGeneratedName(beanDefinition, registry);
}
}
Don't you just inject a Bean? Why do so many ways? In a word, expand on demand
Take a look at how our previous Enable annotation is implemented?
Based on Configuration Class
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import(SchedulingConfiguration.class)
@Documented
public @interface EnableScheduling {
}
@Configuration
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public class SchedulingConfiguration {
@Bean(name = TaskManagementConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME)
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public ScheduledAnnotationBeanPostProcessor scheduledAnnotationProcessor() {
return new ScheduledAnnotationBeanPostProcessor();
}
}
Inject a new BeanPostProcessor through the configuration class, and add support for @Scheduled annotation in BeanPostProcessor
Based on ImportSelector interface
@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;
}
public class AsyncConfigurationSelector extends AdviceModeImportSelector<EnableAsync> {
private static final String ASYNC_EXECUTION_ASPECT_CONFIGURATION_CLASS_NAME =
"org.springframework.scheduling.aspectj.AspectJAsyncConfiguration";
@Override
@Nullable
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;
}
}
}
According to the different code methods configured by the user, select different configuration classes and return the name of the class to be loaded
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";
// 要排除的bean的类型
Class<?>[] exclude() default {
};
// 要排除的bean的名字
String[] excludeName() default {
};
}
Based on ImportBeanDefinitionRegistrar interface
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(AspectJAutoProxyRegistrar.class)
public @interface EnableAspectJAutoProxy {
boolean proxyTargetClass() default false;
boolean exposeProxy() default false;
}
class AspectJAutoProxyRegistrar implements ImportBeanDefinitionRegistrar {
@Override
public void registerBeanDefinitions(
AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
// 直接往registry中注册BeanDefinition
AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry);
AnnotationAttributes enableAspectJAutoProxy =
AnnotationConfigUtils.attributesFor(importingClassMetadata, EnableAspectJAutoProxy.class);
if (enableAspectJAutoProxy != null) {
if (enableAspectJAutoProxy.getBoolean("proxyTargetClass")) {
AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
}
if (enableAspectJAutoProxy.getBoolean("exposeProxy")) {
AopConfigUtils.forceAutoProxyCreatorToExposeProxy(registry);
}
}
}
}
Give you the BeanDefinitionRegistry directly, and inject the BeanDefinition into it yourself, which is suitable for lower-level implementations
Reference blog
[1]https://blog.csdn.net/andy_zhang2007/article/details/96612243
[2]https://blog.csdn.net/qq_26525215/article/details/53524844?utm_medium=distribute.pc_relevant.none-task-blog-baidujs_title-1&spm=1001.2101.3001.4242
ImportAware接口的作用
[3]https://javazhiyin.blog.csdn.net/article/details/101186808