1.综述
很多系统中,架构模式都会产生可重用的bean角色.stereotype允许框架的开发人员为这些bean声明通用的metadata.stereotype可以把下面这些内容组合到一起:
- 默认的范围
- 一组拦截器
- 所有被stereotype标记的bean都有默认的bean EL name
- 所有被stereotype标记的bean都是alternatives
stereotype是一个包含@Stereotype的注解,这个注解中组合了其他的annotations。
比如下面这个stereotype用于标记JSF框架中使用ViewScoped的backingBean:
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.enterprise.inject.Stereotype;
import javax.inject.Named;
import org.omnifaces.cdi.ViewScoped;
@Named
@ViewScoped
@Documented
@Stereotype
@Target({ TYPE, METHOD, FIELD })
@Retention(RUNTIME)
public @interface ViewModel {
}
注:org.omnifaces.cdi.ViewScoped 是一个兼容CDI的viewscoped.作用和JSF的View范围一样.
把他放到bean上,
@ViewModel
public class LoginBean { ... }
2.Default scope for a stereotype
stereotype可以设定beans的默认scope,比如:@RequestScoped
@Stereotype
@Retention(RUNTIME)
@Target(TYPE)
public @interface Action {}
但是Bean也可以自己重写这个默认值:
@Dependent @Action
public class DependentScopedLoginAction { ... }
3.Interceptor bindings for stereotypes
stereotype可以将一组interceptor组合到一起,使用该stereotype标记的beans都会受到这组interceptor的拦截.@RequestScoped
@Transactional(requiresNew=true)
@Secure
@Stereotype
@Retention(RUNTIME)
@Target(TYPE)
public @interface Action {}
这样你的业务代码里就看不到transaction和security等技术相关的内容了
4.用stereotype指定默认name
@RequestScoped
@Transactional(requiresNew=true)
@Secure
@Named
@Stereotype
@Retention(RUNTIME)
@Target(TYPE)
public @interface Action {}
如上所示,stereotype可以使用@Named,这样所有的使用此注解的Bean都会有默认的EL NAME.
现在LoginAction bean 的默认EL NAME就是 loginAction.
5.stereotype和@Alternative
stereotype 也可以使用@Alternative 替换符.@Alternative
@Stereotype
@Retention(RUNTIME)
@Target(TYPE)
public @interface Mock {}
在对应Bean上使用
@Mock
public class MockLoginAction extends LoginAction { ... }
bean.mxl配置,此处仅需如下写入,org.mycompany.testing.Mock就是stereotype注解.这样所有使用@Mock的Bean会被启用.
<beans>
<alternatives>
<stereotype>org.mycompany.testing.Mock</stereotype>
</alternatives>
</beans>
6.Stereotype stacking
@Auditable和@Action两个Stereotype注解是可以再弄一个Stereotype的.这个我们叫他stereotype stacking.下面是个例子:@Auditable
@Action
@Stereotype
@Target(TYPE)
@Retention(RUNTIME)
public @interface AuditableAction {}
7.Built-in stereotypes
CDI defines one standard stereotype, @Model, which is expected to be used frequently in web applications:@Named
@RequestScoped
@Stereotype
@Target({TYPE, METHOD, FIELD})
@Retention(RUNTIME)
public @interface Model {}
Instead of using JSF managed beans, just annotate a bean @Model, and use it directly in your JSF view!