简体   繁体   中英

How access a resource bundle in a @ApplicationScoped Bean

I have a server side event and receive an object in a @MessageDriven bean and I call a method in a @ApplicationScoped bean to prepare an E-Mail in a known locale. I need entries out of the recource bundle to prepare the dynamic message (many Translated Error Messages, the language is coded in the message object).

I try to build a message provider:

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 {

}

The Provider:

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;
    }
}

And I call it like this (simplified):

@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);
    }
}

The FacesContext is always null, because the bean is not triggered by jsf. The object is received as server sided event via JMS. I found nothing about this problem. What is the preferred way in CDI to access a resource bundle in an @ApplicationScoped bean?

I solved it by accessing the resource bundle directly. I think this is best practice, because I found no example/documentation for that special case:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM