Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject producer method that returns String CDI

I would like to inject constant string message to managed bean in JSF web application using CDI, here is producer class:

@Named
@RequestScoped
public class StringProducer {

   @Produces
   @Named("message")    
   @RequestScoped
   public String getMessage() {
      return "Hello World";
   }
}

and here is how it is injected in another managed bean:

@Inject Named("message") String message;

but this always result in exception:

org.jboss.weld.exceptions.UnproxyableResolutionException: WELD-001435 Normal scoped bean int is not proxyable

I tried to wrap String type within Instance like this:

@Inject Named("message") Instance<String> message;

but nothing changed.

like image 771
Hoang Minh Tran Avatar asked Feb 06 '14 23:02

Hoang Minh Tran


People also ask

What is CDI producer?

Java EE CDI introduced a concept called Producer. Producers may be used to create - or produce - bean instances to be consumed by an application. Producers are also able to provide specific interface implementations according to the consumer needs so they are a valid way to support polymorphism in a CDI application.

What is a producer method?

A producer method generates an object that can then be injected. Typically, you use producer methods in the following situations: When you want to inject an object that is not itself a bean. When the concrete type of the object to be injected may vary at runtime.


2 Answers

The problem is your use of the @RequestScoped annotation on the producer method. Remove it and the application will work as expected.

The Request Scoped annotation is used to annotate Beans managed by the container. To do so, the container proxies the object's public methods. Final classes like String are however not proxyable, as pointed out by the exception when running the code on Glassfish 4.0 with Weld 2.0.0 SP1:

WELD-001437 Normal scoped bean class java.lang.String is not proxyable because the type is final or it contains a final method class java.lang.String - Producer Method [String] (...etc.)
like image 154
Seldon Avatar answered Nov 03 '22 07:11

Seldon


Just short info for future readers:

In addition to the four built-in scopes, CDI also supports two pseudo-scopes:

  1. @Singleton
  2. @Dependent

and both above pseudo-scopes have interesting feature: CDI doesn't create a proxy object for them.

So all classes that are not proxyable (e.g. due to being final or due to lack of no-arg public constructor) can be marked with @Singleton or @Dependent - of course if it makes sense.

like image 21
G. Demecki Avatar answered Nov 03 '22 06:11

G. Demecki