在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中的示例代码有两个更具体的例子,大家可以参照一下,分别是@EnableErrorHandler 和 @EnableSpringContext,具体就是开启全局错误处理和Spring上下文管理功能
GitHub地址:https://github.com/ye17186/spring-boot-learn
@EnableXXX作为类似开关的功能,也可以使用@ConditionOnProperty注解实现类似的功能。
————————————————
版权声明:本文为CSDN博主「ye17186」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/ye17186/article/details/88052910