Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
606 views
in Technique[技术] by (71.8m points)

jakarta ee - How to inject a non-serializable class (like java.util.ResourceBundle) with Weld

I want to create a Producer that makes it possible to inject a java.util.ResourceBundle into any class in order to get localized Strings easily. My ResourceBundle-Producer looks like this:

public class ResourceBundleProducer {
  @Inject       
  public Locale locale;

  @Inject       
  public FacesContext facesContext;

  @Produces
  public ResourceBundle getResourceBundle() {
    return ResourceBundle.getBundle("/messages", locale )
  }
}

The Injection of Locale and FacesContext works (took the corresponding producers from the Seam 3 Alpha Source). But unfortunately, ResourceBundle is not Serializable and therefore can't be produced in this way. I'm getting the following Error from Weld when trying to access a JSF-page which calls a bean that uses my ResourceBundle:

Caused by: org.jboss.weld.IllegalProductException: WELD-000054 Producers cannot produce non-serializable instances for injection into non-transient fields of passivating beans\n\nProducer: org.jboss.weld.bean-/D:/Program Files (x86)/GlassFish-Tools-Bundle-For-Eclipse-1.2/glassfishv3/glassfish/domains/teachernews/applications/teachernews/-ProducerMethod-services.producers.ResourceBundleProducer.getResourceBundle()\nInjection Point: field web.PersonHome.bundle

Are there any ways to get my ResourceBundleResolver to work? Or are there any other mechanisms to get a similar functionality? Thanks in advance!

EDIT:

Okay, i'll spent some of my hardly earned points ;) Will also accept a good workaround for this issue!

I got another example where creating a Producer doesn't work: a FlashProducer. A FacesContext-Flash also cannot be produced because Flash isn't serializable.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well, First of all ResourceBundle is not Serializable. See here. And The message is clear

cannot produce non-serializable instances for injection into non-transient fields of passivating beans

passivating beans ??? I Think web.PersonHome is Either a Stateful Session Bean or a @ConversationScoped bean. Am i right ??? If so you should mark your bundle property as transient

private transient @Inject ResourceBundle bundle;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...