【发布时间】:2019-11-28 21:08:11
【问题描述】:
我有一个服务器端事件并在@MessageDriven bean 中接收一个对象,然后我调用@ApplicationScoped bean 中的一个方法来准备一个已知语言环境中的电子邮件。我需要资源包中的条目来准备动态消息(许多翻译错误消息,语言在消息对象中编码)。
我尝试构建一个消息提供者:
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
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.inject.Qualifier;
@Qualifier
@Documented
@Retention(RUNTIME)
@Target({ TYPE, FIELD, METHOD, PARAMETER })
public @interface MessageBundle {
}
提供者:
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import javax.enterprise.inject.Produces;
import javax.inject.Named;
@Named
public class MessageProvider {
private ResourceBundle bundle;
public MessageProvider() {
this.bundle = null;
}
@Produces @MessageBundle
public ResourceBundle getBundle() {
if (bundle == null) {
FacesContext context = FacesContext.getCurrentInstance();
bundle = context.getApplication()
.getResourceBundle(context, "msgs");
}
return bundle;
}
}
我这样称呼它(简化):
@Named
@ApplicationScoped
public class SmtpSenderBean {
@EJB
private SendMail sendmail;
@Inject @MessageBundle
private ResourceBundle bundle;
public void send(Email mail, int errorCode){
String subjectMsg = bundle.getString("event.smtp.subject");
String bodyMsg = bundle.getString("event.smtp.body");
mail.setSubject(MessageFormat.format(subjectMsg, errorCode));
mail.setBody(MessageFormat.format(bodyMsg, errorCode))
sendmail.send(mail);
}
}
FacesContext 始终为空,因为 bean 不是由 jsf 触发的。该对象作为服务器端事件通过 JMS 接收。我没有发现这个问题。在 CDI 中访问 @ApplicationScoped bean 中的资源包的首选方式是什么?
【问题讨论】:
-
检查这里:deltaspike.apache.org 可能在那里非常有用