如何访问 @ApplicationScoped Bean 中的资源包

How access a resource bundle in a @ApplicationScoped Bean

我有一个服务器端事件并在@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始终为null,因为bean不是jsf触发的。该对象通过 JMS 作为服务器端事件接收。我没有发现这个问题。在 CDI 中访问 @ApplicationScoped bean 中的资源包的首选方式是什么?

我直接访问资源包解决了。我认为这是最佳做法,因为我发现没有 example/documentation 适合这种特殊情况:

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