我想将 CDI 视为以下内容:-
预选赛
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({
ElementType.METHOD,
ElementType.FIELD,
ElementType.PARAMETER,
ElementType.TYPE
})
@Documented
public @interface MessageTemplate {
@Nonbinding
String baseName();
@Nonbinding
Locale locale() default Locale.ENGLISH;
@Nonbinding
String key();
}
制片人
public class CustomizedProducer {
@Produces
@MessageTemplate(baseName = "",
key = "")
public String createMessageTemplate(final InjectionPoint ip) {
MessageTemplate configure = null;
ResourceBundle bundle = null;
try{
configure = ip.getAnnotated().getAnnotation(MessageTemplate.class);
bundle = ResourceBundle.getBundle(configure.baseName(),
configure.locale());
return bundle.getString(configure.key());
} finally{
configure = null;
bundle = null;
}
}
}
服务配置
public class MyServiceConfigure {
@Inject
@MessageTemplate(baseName = "com.my.domain.MyProp",
key = "appDescription")
private String appDescription;
@Inject
@MessageTemplate(baseName = "com.my.domain.MyProp",
key = "okButtonLabel")
private String okButtonLabel;
//Getter
}
工人阶级
public class MyService {
@Inject
private MyServiceConfigure configure;
public void doSomething() {
System.out.println(configure.getAppDescription());
System.out.println(configure.getOkButtonLabel());
}
}
关于上面的编码,您可以使用java.util.Properties
代替java.util.ResourceBundle
并为限定符提供默认成员。
如果您在 JavaEE 6 下运行这些,CDI 已经为您启用。只需将空 beans.xml 放入 META-INF 或 WEB-INF。如果您在 Java SE 下运行,您可能需要一些进一步的工作,如Weld 网站及其文档中所述。
我正在使用 CDI 作为我当前生产项目的主要部分,它运行良好。
编辑:-
使用 CDI 的好处是作用域,我们可以生成@MessageTemplate
as @ApplicationScope
、@SessionScoped
、@RequestScoped
或@ConversationScoped
伪作用域为@Singleton
or@Depenendent
如果您将 MyServiceConfigure 注释为@Named
,那么它也可以在 JSF 中使用。