Limited generics with CDI

The JSR-299 specification reads in clause 3.1:

If the managed bean class is a generic type, it must have @Dependent scope. If a declared managed bean with a parameterized bean class declares any scope except @Dependent, the container automatically detects the problem and treats it as a detection error.

Effectively means you cannot do this:

@Named @SessionScoped or @RequestScoped or similar public class MyProducer<T> {...} 

What are the technical reasons for this decision?

Will it be fixed in an upcoming version of CDI, if possible?

Is there any best practice to work / work with this?

thanks

EDIT - A workaround that I can often use is to introduce a common POJo bean into the bean with the required scope. Often, but not always.

+7
source share
2 answers

Here's a generic, bean-independent class:

 @ApplicationScoped public class FavouriteChooser<T> { public T getFavourite() { // ... } } 

How many instances of this bean will be in the application?

Here is the injection site:

 @Inject private FavouriteChooser<String> favouriteWord; 

And one more thing:

 @Inject private FavouriteChooser<Integer> favouriteNumber; 

Do you want to change your answer ?: D

Oh, and here's another:

 @Inject private FavouriteChooser<CharSequence> favouriteLetters; 

EDIT. If you want a solution, I would suggest making your abstract abstract class and adding specific subclasses that bind the type. So:

 public abstract class MyProducer<T> {...} @Named @SessionScoped public class MyStringProducer extends MyProducer<String> {} @Named @SessionScoped public class MyIntegerProducer extends MyProducer<Integer> {} 

This is a pattern, but there are only three lines for each type. Keep in mind that this will give you one instance per session for each type that you might not need.

+13
source

All scope-independent beans should be approximated - AFAIK is not possible in generic types.

UPDATE:

I would like to explain this in more detail, but I won’t ;-) Weld uses javassist , and they claim that proxy generic types are possible in principle - although they are not directly supported by the toplevel API. But we are talking about a specification, not a Weld implementation ...

Can someone else fill in the gap?

+2
source

All Articles