CDI模糊依存关系
我有一个 @SessionScoped @Named
bean和一个用于用户对象的 @Producer
方法:
I have a @SessionScoped @Named
bean with a @Producer
method for a user object:
@Named @SessionScoped
public class UserBean implements Serializable
{
//...
@Named @Produces @LoggedIn @SessionScoped
public MyUser getCurrentUser() {return user;}
}
这在我的设置(JBoss-7.1.1-Final)中正常工作,并且可以使用#{currentUser.name} 从JSF页面访问用户字段。 code>。限定符为
org.jboss.seam.security.annotations.LoggedIn
。现在,我想在另一个 @Named
Bean中的字段中, @Inject
该用户:
This works fine in my setup (JBoss-7.1.1-Final) and it's no problem to access the user fields from JSF pages with #{currentUser.name}
. The qualifier is org.jboss.seam.security.annotations.LoggedIn
. Now I want to @Inject
this user in a field in another @Named
Bean:
@Named
public class FavBean implements Serializable
{
private @Inject @LoggedIn MyUser currentUser;
}
这给了我错误:
org.jboss.weld.exceptions.DeploymentException:
WELD-001409 Ambiguous dependencies for type [MyUser] with qualifiers [@Default] at
injection point [[field] @Inject @LoggedIn test.FavBean.currentUser].
Possible dependencies [[Managed Bean [class test.ejb.MyUser] with qualifiers
[@Any @Default],
Producer Method [MyUser] with qualifiers [@Any @Default] declared as [[method]
@Named @Produces @LoggedIn @SessionScoped public test.UserBean.getCurrentUser()]]]
我不了解第一个依赖项 Managed Bean [类test.ejb.MyUser]
此类是简单的 @Entity
并部署在EAR的ebb.jar中。作为一种解决方法,我目前正在注入 UserBean
从那里获取用户。
I don't understand the first dependency Managed Bean [class test.ejb.MyUser]
This class is a simple @Entity
and deployed in an ebb.jar in a EAR. As a workaround I'm currently injecting the UserBean
get the user from there.
这是因为CDI按类型搜索bean,并且您的实体和生产者方法返回相同的类型。这就是为什么它含糊不清的原因。
This is because CDI searches for beans by type and your entity and the producer method return the same type. That's why it is ambiguous.
您需要定义一个新的限定词,并使用生产者方法对其进行注释。
You need to define a new qualifier and annotate it with your producer method.
@Qualifier
@Retention(RUNTIME)
@Target({METHOD, FIELD, PARAMETER, TYPE})
public @interface CurrentUser {
}
将此注释添加到您的生产者方法:
Add this annotation to your producer method:
@Named @Produces @CurrentUser @LoggedIn @SessionScoped
public MyUser getCurrentUser() {return user;}