《springboot编程思想》将spring enable注解模块分类“注解驱动”和“接口编程”。其中@Configoration、@Component被称作“注解驱动”,@ImportSelector、@ImportBeanDefinitionRegister被称作“接口编程”。
通过ImportSelector模拟实现@Enable模块驱动,通过配置加载接口的不同实例对象。
工程结构

- IHello接口
public interface IHello {
String hello();
}
IHello的两个实现:
public class HelloKitty implements IHello {
public String hello() {
return "hello kitty";
}
}
public class HelloWorld implements IHello {
public String hello() {
return "hello world";
}
}
注解定义:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import(HelloImportSelector.class)
public @interface EnableHello {
String value();
}
SelectImportor实现:
public class HelloImportSelector implements ImportSelector {
public String[] selectImports(AnnotationMetadata annotationMetadata) {
System.out.println("HelloImportSelector...");
Map<String, Object> annotationAttributes = annotationMetadata.getAnnotationAttributes(EnableHello.class.getName());
String value = (String) annotationAttributes.get("value");
if ("world".equals(value)) {
//读取注解value值,如果等于world实例化HelloWorld
return new String[]{HelloWorld.class.getName()};
} else if ("kitty".equals(value)) {
//读取注解value值,如果等于world实例化HelloKitty
return new String[]{HelloKitty.class.getName()};
}
return new String[0];
}
}
启用@EnableHello注解
@EnableWebMvc
@Configuration
//@EnableHello(value = "kitty")
@EnableHello(value = "world")
@ComponentScan(basePackages = "controller")
public class SpringWebMVCConfiguration {
}
注入IHello实例
@Controller
public class HelloController {
@Resource
private IHello hello;
@PostConstruct
public void init() {
System.out.println("hello..." + hello);
}
@RequestMapping
@ResponseBody
public String hello() {
return hello.hello();
}
}
测试注入IHello实例对象:
curl http://localhost:8080
hello world
输出hello world,表示注入的为HelloWorld对象。
网友评论