Spring Boot实现简单的Enable***功能

  在使用SpringBoot的时候,我们经常使用Enable**开启某个功能,比如@EnableSwagger2@EnableJpaAuditing等,这是怎么做的呢,之前其实就了解过了,今天刚好有空做个分享,拿@EnableWebSecurity举例: 

@Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME)
@Target(value = { java.lang.annotation.ElementType.TYPE })
@Documented
@Import({ WebSecurityConfiguration.class,
        SpringWebMvcImportSelector.class })
@EnableGlobalAuthentication
@Configuration
public @interface EnableWebSecurity {

    /**
     * Controls debugging support for Spring Security. Default is false.
     * @return if true, enables debug support with Spring Security
     */
    boolean debug() default false;
}

  在上面的源码中我们可以看到使用@Import导入了两个类文件,一个是我们常用的配置类,另外一种是Selector类文件,我们看一下这个SpringWebMvcImportSelector类:

class SpringWebMvcImportSelector implements ImportSelector {

    /*
     * (non-Javadoc)
     *
     * @see org.springframework.context.annotation.ImportSelector#selectImports(org.
     * springframework .core.type.AnnotationMetadata)
     */
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        boolean webmvcPresent = ClassUtils.isPresent(
                "org.springframework.web.servlet.DispatcherServlet",
                getClass().getClassLoader());
        return webmvcPresent
                ? new String[] {
                        "org.springframework.security.config.annotation.web.configuration.WebMvcSecurityConfiguration" }
                : new String[] {};
    }
}

该类实现了ImportSelector,实现了该类在Spring Boot项目启动的时候会执行selectImports方法把需要纳入Spring管理的类,进行加载初始化。

posted @ 2019-03-12 13:53  meetzy  阅读(631)  评论(0编辑  收藏  举报