在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上下文管理功能