【问题标题】:How access a resource bundle in a @ApplicationScoped Bean如何访问 @ApplicationScoped Bean 中的资源包
【发布时间】: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 中的资源包的首选方式是什么?

【问题讨论】:

标签: java jsf wildfly cdi


【解决方案1】:

我通过直接访问资源包解决了这个问题。我认为这是最佳实践,因为我没有找到该特殊情况的示例/文档:

@Produces @MessageBundle
public ResourceBundle getBundle() {
    if (bundle == null) {
        bundle = ResourceBundle.getBundle("com.example.msgs");
    }
    return bundle;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-07
    • 1970-01-01
    • 1970-01-01
    • 2016-06-18
    相关资源
    最近更新 更多