Spring自定义注解扫描

创建注解和对象

1.例子

/**
自定义注解 ,作用当spring扫描类上面有该注解时自动创建bean到spring容器中
**/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.ANNOTATION_TYPE})
public @interface MyAnnotion {

}
@MyAnnotion
public class HelloWord {
    private String name = "lsr";
    public String say(){
        return "hello "+name;
    }
}

2.定义DefinitionRegistryPostProcessor

@Configuration
public class DefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory arg0) throws BeansException {

    }

    /**
     * 先执行postProcessBeanDefinitionRegistry方法
     * 在执行postProcessBeanFactory方法
     */
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
       扫描自定义注解
        ClassPathBeanDefinitionScanner scanner = new 
      ClassPathBeanDefinitionScanner(registry);
        // bean 的名字生成规则在AnnotationBeanNameGenerator
        scanner.setBeanNameGenerator(new AnnotationBeanNameGenerator());
        // 设置哪些注解的扫描
        scanner.addIncludeFilter(new AnnotationTypeFilter(MyAnnotion.class));
        scanner.scan("com.anyly");
        // 注意helloWord已经注册到容器中. 细看AnnotationBeanNameGenerator 的    
        generateBeanName()
    }
    }

3.测试bean是否在spring容器中

  public static void main(String[] args) {
        ApplicationContext applicationContext = SpringApplication.run(ApplicationBoot.class);
        HelloWord helloWord = applicationContext.getBean("helloWord", HelloWord.class);
        System.out.println(helloWord.say());
    
    }

注意:默认扫描到的对象bean名字是开头大些转小写例如 HelloWord -> helloWord

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容