Spring @Enable 模块驱动(一.注解驱动实现)
相信很多小伙伴都使用过Spring,而且经常看到使用Spring定义的一些注解,比如@EnableFeignClients,@EnableZuulProxy,@EnableEurekaServer,使用这些注解就可以激活相对应得模块,看到这里好奇心大的小伙伴,一定想知道为什么打这么一个注解就可以激活相应的模块,今天我们来讨论下这些注解背后的故事。
@Enable模块驱动,按照其实现分为注解驱动 和接口编程 所以下面我们就来看下这两种方式实现
- 基于注解驱动实现@Enable模块
首先我们去找个Spring Framework中的例子来看一看
相信用过@Import的小伙伴都知道它的作用,我们去看看DelegatingWebMvcConfiguration.class的源码看看它究竟在干嘛
根据它的注释,代码和注解可以看出这是一个@Configuration类,这种实现方式,相当于给我们提供了一个很好的例子。所以下面我们也来实现一个自己的@Enable模块驱动(注解驱动实现)
package com.example.demo.annotation;
import com.example.demo.configurations.EatConfiguration;
import org.springframework.context.annotation.Import;
import java.lang.annotation.*;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(EatConfiguration.class)
public @interface EnableEat {
}
package com.example.demo.configurations;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
@Configurable
public class EatConfiguration {
@Bean
public String eatRice(){
return "i can eat rice";
}
}
package com.example.demo;
import com.example.demo.annotation.EnableEat;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
@EnableEat
@Slf4j
@Configuration
public class DemoApplication {
public static void main(String[] args) {
//构建Annotation配置驱动Spring上下文
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
//注册当前引导类到Spring的上下文
context.register(DemoApplication.class);
//启动上下文
context.refresh();
String eatRice = context.getBean("eatRice", String.class);
log.info("result==================:[{}]", eatRice);
//关闭上下文
context.close();
}
}
如图所示我们成功的实现注解驱动实现的@Enable模块驱动,
在下篇笔记中我们将实现基于接口编程实现@Enable模块。如有错误欢迎各位大佬指出,谢谢,
参考书籍:SpringBoot编程思想