CDI限制性仿制药 [英] Restricted generics with CDI

查看:177
本文介绍了CDI限制性仿制药的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JSR-299规范在§3.1中规定:

The JSR-299 specification states in §3.1:


如果托管bean类是通用类型,则它必须具有范围
@独立如果具有参数化bean类的托管bean声明
除@Dependent之外的任何范围,容器将自动检测到
的问题,并将其视为定义错误。

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?

在即将到来的CDI版本中是否会有机会补救?

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

有最好的做法来处理/解决这个问题吗?

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

谢谢

编辑 - 我经常可以使用的解决方法是将一个通用POJO-bean注入具有所需范围的bean中。

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.

推荐答案

这是一个通用的,不依赖的bean类:

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

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

应用程序中有多少个bean的实例?

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

这是一个注入站点:

@Inject
private FavouriteChooser<String> favouriteWord;

另请参阅:

@Inject
private FavouriteChooser<Integer> favouriteNumber;

您要更改答案吗? :D

Would you like to change your answer? :D

噢,这是另一个:

@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.

这篇关于CDI限制性仿制药的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆