spring boot:2.0.3
jdk:1.8
自动创建bean即大家常见的这样的注解。 @EnableWebMvc @EnableCacheing 等等
具体实现方式有3种。
方式1:使用@Import + @Configuration 组合
@Configuration
public class HelloConfiguration {
@Bean
public HelloBean helloBean() {
return new HelloBean();
}
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(HelloConfiguration.class)
public @interface EnableHelloWithConfiguration {
}
方式2:使用@Import + ImportSelect实现类 的组合
public class HelloSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
ObjectMapper om = new ObjectMapper();
try {
System.out.println("importingClassMetadata..." + om.writeValueAsString(importingClassMetadata));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return new String[]{
HelloBean.class.getName()};
}
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(HelloSelector.class)
public @interface EnableHelloWithSelector {
}
方式3:使用@Import + ImportBeanDefinitionRegistrar 实现类的方式
/**
* 同时可以继承 ResourceLoaderAware, BeanFactoryAware 等获取其他信息
*/
public class HellobeanRegistry implements ImportBeanDefinitionRegistrar {
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
ObjectMapper om = new ObjectMapper();
try {
System.out.println("importingClassMetadata..." + om.writeValueAsString(importingClassMetadata));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(registry, false);
//方式一 直接使用对应的Bean.class 过滤
TypeFilter helloServiceFilter = new AssignableTypeFilter(HelloBean.class);
scanner.addIncludeFilter(helloServiceFilter);
//方式二 使用注解过滤,即在目标bean上添加特定的注解
// scanner.addIncludeFilter(new AnnotationTypeFilter(HelloBeanAnnotation.class));
scanner.scan("com.illegalaccess.tutorials.spring.enable");
}
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(HellobeanRegistry.class)
public @interface EnableHelloWithRegistry {
}
完整代码建:https://github.com/Roronoa-Zoro/tutorials/tree/master/spring-enable