从Spring 2开始,为了响应JDK1.5推出的注解功能,Spring开始大量加入注解来替代xml配置。Spring的注解主要用来配置和注入Bean,以及AOP相关配置(@Transactional)。随着注解的大量使用,尤其相同的多个注解用到各个类或方法中,会相当繁琐。这就是所谓的样板代码(boilerplate code),是Spring设计原则中要消除的代码。
所谓元注解其实就是可以注解到别的注解上的注解,被注解的注解称之为组合注解,组合注解具备注解其上的元注解的功能。Spring的很多注解都可以作为元注解,而且Spring本身已经有很多组合注解,如@Configuration就是一个组合@Component注解,表明这个类其实也是一个Bean。
我们前面的章节里大量使用@Configuration和@ComponentScan注解到配置类上,如果你跟着本文一直在敲代码的话是不是觉得已经有点麻烦了呢?下面我将这两个元注解组合成一个组合注解,这样我们只需写一个注解就可以表示两个注解。
3.5.2 示例
(1)示例组合注解。
package com.wisely.highlight_spring4.ch3.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration //组合Configuration元注解
@ComponentScan //组合ComponentScan元注解
public @interface WiselyConfiguration {
String [] value () default {} ; //覆盖value参数。
}
(2)演示服务Bean。
package com.wisely.highlight_spring4.ch3.annotation;
import org.springframework.stereotype.Service;
@Service
public class DemoService {
public void outputResult(){
System.out.println("从组合注解配置照样获得的bean");
}
}
(3)新的配置类。
package com.wisely.highlight_spring4.ch3.annotation;
@WiselyConfiguration("com.wisely.highlight_spring4.ch3.annotation")//使用@WiselyConfiguration组合注解替代@Configuration和@ComponentScan
public class DemoConfig {
}
(4)运行。
package com.wisely.highlight_spring4.ch3.annotation;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(DemoConfig.class);
DemoService demoService = context.getBean(DemoService.class);
demoService.outputResult();
context.close();
}
}