7.12. decorators
解码器截获来自特定 Java 接口的调用,并了解与该接口连接的所有语义。解码器可用于为某些业务问题建模,但并不具有拦截器的一般性。decorator 是一种 Bean 甚至抽象类,用于实施它解密的类型,并标上 @Decorator
标注。要在上下文和依赖注入应用程序中调用解码器,必须在 beans.xml
文件中指定它。
示例:通过 beans.xml
清理一个 Decorator
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_2_0.xsd"> <decorators> <class>org.mycompany.myapp.LargeTransactionDecorator</class> </decorators> </beans>
该声明主要有两个目的:
- 它可让您在系统中为解码器指定排序,以确保确定性行为。
- 它可让您在部署时启用或禁用 decorator 类。
解码器必须具有一个 @Delegate
注入点,才能获得对解码对象的引用。
示例:解码器类
@Decorator public abstract class LargeTransactionDecorator implements Account { @Inject @Delegate @Any Account account; @PersistenceContext EntityManager em; public void withdraw(BigDecimal amount) { ... } public void deposit(BigDecimal amount); ... } }
从 CDI 1.1 开始,可以使用 @Priority
注释为整个应用启用 decorator。
在使用 beans.xml
文件启用解码器之前,调用使用 @Priority
启用的 decorators。较低优先级的值先调用。
注意
通过 @Priority
启用 decorator 并且同时被 beans.xml 调用
,这会造成不可移植的行为。因此,应避免这种启用组合,以便在不同的上下文和依赖注入实施之间保持一致的行为。