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
399 views
in Technique[技术] by (71.8m points)

java - Restricted generics with CDI

The JSR-299 specification states in §3.1:

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

Effectively meaning that you can't do this:

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

What are the technical reasons for this decision?

Will it be remedied in an upcoming version of CDI by any chance?

Is there a best practice for dealing with /working around this?

Thank you

EDIT - a workaround I can often use is to inject a generic POJO-bean into a bean with the needed scope. Often, but not always.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Here's a generic, non-dependent bean class:

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

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

Here is an injection site:

@Inject
private FavouriteChooser<String> favouriteWord;

And here's another:

@Inject
private FavouriteChooser<Integer> favouriteNumber;

Would you like to change your answer? :D

Ooh, and here's another:

@Inject
private FavouriteChooser<CharSequence> favouriteLetters;

EDIT. If you want a solution, i would suggest making your generic class abstract, and adding concrete subclasses which 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> {}

It's boilerplate, but it's only three lines per type. Bear in mind that would give you one instance per session per type, which you might not want.


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

...