spring boot 自定义@EnableXXX功能

版权声明:原创欢迎转载,转载请注明出处 https://blog.csdn.net/ye17186/article/details/88052910

在springboot中,我们开启一项功能是,常常用到@Enable***注解,例如@EnableAsync、@EnableCaching等等。下面我们来自己实现一个该功能。

一、定义一个我们需要装配的功能

/**
 * @author ye17186
 * @version 2019/3/1 11:31
 */
public class MyConfiguration {

    @Bean
    public String testBean() {
        return "this is my test bean.";
    }
}

二、定义个@Enable注解,实现动态加载它

/**
 * @author ye17186
 * @version 2019/3/1 11:31
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(MyConfiguration.class)
public @interface EnableMyConfig {
}

其中的核心就是@Import功能

三、使用,启动类上,加入@EnableMyConfig即可

@Slf4j
@SpringBootApplication
@EnableMyConfig
public class YCloudsServiceDemoApplication {

    public static void main(String[] args) {
        ApplicationContext context = SpringApplication
            .run(YCloudsServiceDemoApplication.class, args);

        // 验证我们的bean是否成功注入
        log.info(context.getBean("testBean", String.class));
    }
}

四、验证

启动项目之后,可以看到控制台输出"this is my test bean.",说明我们的功能已成功实现

GitHub地址:https://github.com/ye17186/spring-boot-learn

猜你喜欢

转载自blog.csdn.net/ye17186/article/details/88052910