是否可以使用CDI注入EJB实现而不是其接口?

Ton*_*ony 11 java dependency-injection ejb cdi weld

我的配置是:Wildfly 8.2.0,Weld

是否可以在bean中注入,而不是在CDI的接口中注入?

@Stateless
class Bean implements IBean {
...
}    

interface IBean {
...
}

@SessionScoped
class Scoped {
   @Inject
   Bean bean; //Fail

   @Inject
   IBean iBean; //OK
}
Run Code Online (Sandbox Code Playgroud)

编辑:

我在上一个问题中的更多信息: 无状态EJB实现接口注入失败

Tar*_*rik 20

是的,您可以,但是当EJB注入业务视图时,您公开的唯一业务视图是@Local实现接口时的默认视图(IBean在您的情况下是本地业务接口).因此,如果要自己注入bean,则需要告诉容器您正在使用无接口视图.

在您的示例中,如果您仍想要实现接口并注入Bean,则应使用@LocalBean注释,这意味着bean公开了无接口视图:

@Stateless
@LocalBean // <-- no-interface view
class Bean implements IBean {
...
}  

interface IBean {
....
}

@SessionScoped
class Scoped {
   @Inject
   Bean bean; //Should be OK
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您不想实现任何接口,那么bean默认定义一个No-Interface视图:

@Stateless
class Bean {
...
}  

@SessionScoped
class Scoped {
   @Inject
   Bean bean; //OK
}
Run Code Online (Sandbox Code Playgroud)

也可以看看: