我们看看spring的@Service的源码:可看出@Service注解是由几个注解组合的包含@Component;
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {
String value() default "";
}
下面的例子不见得举得合适,但是可简单演示元注解的作用
组合@Configuration,@PropertySource注解为一个注解@WiselyMetaAnnotation
package com.wisely.meta;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@PropertySource("com/wisely/javaconfig/test.properties")
public @interface WiselyMetaAnnotation {
}
去除DemoConfig上的配置,使用新定义的组合元注解
package com.wisely.meta;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
//@Configuration //声明是一个配置类
//@PropertySource("com/wisely/javaconfig/test.properties")
@WiselyMetaAnnotation
public class DemoConfig {
@Bean //声明是一个bean
public DemoService demoBean(Environment environment){
DemoService demoService = new DemoService();
demoService.setWord(environment.getProperty("wisely.word"));
return demoService;
}
}
package com.wisely.meta;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext("com.wisely.meta");
DemoService demoService = context.getBean(DemoService.class);
System.out.println(demoService.sayHello());
context.close();
}
}
输出结果
Hello World
与<<02点睛Spring4.1-Java Config>>结果保持一致
原文:http://wiselyman.iteye.com/blog/2213386