一、元注解
元注解是指一个能声明在其他注解上的注解,如果一个注解标注在其他注解上,那么它就是元注解。例如
- @Documented
- @Inherited
- @Repeatable (java 8)
- @Component ( Spring)
二、Spring模式注解
管理和存储某种领域对象的注解,Spring核心部分提供了几种模式注解:
- @Component
- @Service
- @Controller
- @RestController
- @Configuration
Java语言规范,Annotation不允许集成,没有派生子类的negligible,因此Spring采用元注解方式实现注解的派生。
以@RestController为例:
自定义派生注解
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component // 测试多层次 @Component派生,请将当前注释
public @interface StringRepository {
/**
* 属性方法必须与 {@link Component#value()} 保持一致
* @return Bean 的名称
*/
String value() default "";
}
@StringRepository("chineseNameRepository")
public class NameRepository {
/**
* 查找所有的名字
*
* @return non-null List
*/
public List<String> findAll() {
return Arrays.asList("张三", "李四", "小马哥");
}
}
public class DerivedComponentAnnotationBootstrap {
static {
// 解决 Spring 2.5.x 不兼容 Java 8 的问题
// 同时,请注意 Java Security 策略,必须具备 PropertyPermission
System.setProperty("java.version", "1.7.0");
}
public static void main(String[] args) {
// 构建 XML 配置驱动 Spring 上下文
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext();
// 设置 XML 配置文件的位置
context.setConfigLocation("classpath:/META-INF/spring/context.xml");
// 启动上下文
context.refresh();
// 获取名称为 "chineseNameRepository" Bean 对象
NameRepository nameRepository = (NameRepository) context.getBean("chineseNameRepository");
// 输出用户名称:[张三, 李四, 小马哥]
System.out.printf("nameRepository.findAll() = %s \n", nameRepository.findAll());
}
}