spring scanner 扫描器 使用 demo

其他技术

2018-05-20

40

0

技术:java8 + spring boot 2.0.2.RELEASE

运行环境:IDEA 15.2 + jdk8 + windows 7

demo功能:提供一个spring scanner 包扫描器 使用demo。 打印出标记 

org.springframework.stereotype.Component 的bean

1. 创建spring boot项目为demo

参考 https://projects.spring.io/spring-boot/#quick-start

2. 添加自定义扫描器DemoClassPathScanner.java

public class DemoClassPathScanner extends ClassPathBeanDefinitionScanner {
    public DemoClassPathScanner(BeanDefinitionRegistry registry) {
        super(registry, false);
        addIncludeFilter(new AnnotationTypeFilter(Component.class));
    }

    @Override
    protected Set doScan(String... basePackages) {
        printStart();
        final Set beanDefinitionHolders = super.doScan(basePackages);
        if (beanDefinitionHolders == null || beanDefinitionHolders.isEmpty()) {
            System.out.println("no any beans found");
            this.printEnd();
            return Collections.emptySet();
        }

        beanDefinitionHolders.forEach(x -> {
            System.out.println("bean name=" + x.getBeanName() + ", class=" + x.getBeanDefinition().getBeanClassName() + " found");
        });
        this.printEnd();
        return beanDefinitionHolders;
    }

    void printStart() {
        System.out.println("========================beans start====================================");
    }

    void printEnd() {
        System.out.println("========================beans end====================================");
    }

    @Override
    protected boolean checkCandidate(String beanName, BeanDefinition beanDefinition) throws IllegalStateException {
        return true;
    }
}

3. 添加使用扫描器初始化器

public class EnablePrintAllBeansInitializer implements ImportBeanDefinitionRegistrar {
    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
        new DemoClassPathScanner(beanDefinitionRegistry).doScan("com.demoworld");
    }
}

4. 添加启用自定义扫描器注解

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@Import({EnablePrintAllBeansInitializer.class})
public @interface EnablePrintAllBeans {
}

4. 测试

@Controller
@EnableAutoConfiguration
@EnablePrintAllBeans
public class Application {

    @RequestMapping("/")
    @ResponseBody
    String home() {
        return "Hello World!";
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

欢迎添加微信,互相学习↑↑↑ -_-

发表评论

全部评论:0条

白老虎

programming is not only to solve problems, ways to think