Spring框架参考手册(4.2.6版本)翻译——第三部分 核心技术 6.10.2 元注解

6.1.1 元注解

Spring提供的许多注都可以在您自己的代码中用作元注。元注只是一个可以应用于另一个注的注。例如,上面提到的@Service是使用@Component进行元注的:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component // Spring will see this and treat @Service in the same way as @Component
public @interface Service {

    // ....
}

元注也可以进行组合来创建组合注。例如,Spring MVC@RestController注释由@Controller@ResponseBody组成。

此外,组合注可以随意地从元注重新声明属性允许用户进行定制。当您只想暴露元注属性的子集时,这可能特别有用。 例如,以下是自定义@Scope,它将作用域名称硬编码session,但仍允许proxyMode的自定义。

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Scope("session")
public @interface SessionScope {

    ScopedProxyMode proxyMode() default ScopedProxyMode.DEFAULT;
}
然后可以使用@SessionScope而不声明proxyMode,如下所示:
@Service
@SessionScope
public class SessionScopedUserService implements UserService {
    // ...
}

或者对于proxyMode使用重写值,如下所示:

@Service
@SessionScope(proxyMode = ScopedProxyMode.TARGET_CLASS)
public class SessionScopedService {
    // ...
}

有关更多详细信息,请参阅Spring注解编程模型

猜你喜欢

转载自www.cnblogs.com/springmorning/p/10432723.html