天天看点

springboot 自定义注解实现bean自动装配

以下内容是我根据,记录日志是否进行选择启用,而设计的。

第一步:创建注解

/**
 * @author wwz
 */
@Target(ElementType.TYPE)
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Import(AopLogRegister.class)
public @interface AutoImport {
    /**
     * 是否启用,默认true
     * @return
     */
    boolean isEnabled() default true;

    /**
     * 自动装配的类
     * @return
     */
    Class<?>[] value() ;
}      

第二步:AopLogRegister类实现ImportBeanDefinitionRegistrar实现bean的注册

/**
 * @author wwz
 */
@Data
@Slf4j
public class AopLogRegister implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        if(importingClassMetadata.hasAnnotation(AutoImport.class.getName())){
            MergedAnnotations mergedAnnotations = importingClassMetadata.getAnnotations();
            MergedAnnotation mergedAnnotation = mergedAnnotations.get(AutoImport.class);
            if(mergedAnnotation == null){
                return;
            }
            //注解上是否启用
            if( mergedAnnotation.getBoolean("isEnabled")){
                if(log.isInfoEnabled()){
                    log.info(">>>>start auto import bean definition<<<<");
                }
                //获取AutoImport上value配置的class数组
                Class<?>[] values = mergedAnnotation.getClassArray("value");
                for(Class value:values){
                    RootBeanDefinition beanDefinition = new RootBeanDefinition(value);
                    registry.registerBeanDefinition(value.getSimpleName(),beanDefinition);
                }
                if(log.isInfoEnabled()){
                    log.info(">>>>end auto import bean definition<<<<");
                }
            }

        }

    }

}

      

第三步:在启动类加上如上注解

@AutoImport(value= {XXXX.class})

springboot 自定义注解实现bean自动装配

 切记XXXX.class 不要配置可装配的注解。形如:@Component,@Configure,@Controller等。不然以上代码自动装配的意义就没有了。

然后你可以在注解上进行,配置任何属性。达到自己的目的。

其实这个用注解自动装配bean。最主要的就是

AopLogRegister类实现ImportBeanDefinitionRegistrar

继续阅读