我有以下代码来管理两种存储库.这两个存储库类都继承了一个接口,以便重新初始化其资源.
public interface CachingRepository { public void invalidateCache(); }
全球应用范围的回购:
@Named("globalRepo") @ApplicationScoped public class GlobalRepository implements CachingRepository { private List<Category> categories; ... @Override public void invalidateCache() { categories = null; } ... }
每个用户,会话范围的回购:
@Named("userRepo") @SessionScoped //@Stateful // <- NOTE HERE public class UserRepository implements CachingRepository,Serializable { private List<MyFile> files; @Override public void invalidateCache() { files = null; } ... }
当注入(不用@Stateful)到上下文中
@Named @ViewScoped public class MyHandler implements Serializable { @Inject private UserRepository userRepo; ... }
有用.但是,当将@Stateful添加到UserRepository类时,部署将失败,并显示以下异常:
Caused by: org.jboss.weld.exceptions.DeploymentException: WELD-001408 Unsatisfied dependencies for type [UserRepository] with qualifiers [@Default] at injection point [[field] @Inject private de.company.project.pack.MyHandler.userRepo] at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:275) at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:244) at org.jboss.weld.bootstrap.Validator.validateBean(Validator.java:107) at org.jboss.weld.bootstrap.Validator.validateRIBean(Validator.java:127) at org.jboss.weld.bootstrap.Validator.validateBeans(Validator.java:346) at org.jboss.weld.bootstrap.Validator.validateDeployment(Validator.java:331) at org.jboss.weld.bootstrap.WeldBootstrap.validateBeans(WeldBootstrap.java:366) at org.jboss.as.weld.WeldContainer.start(WeldContainer.java:83) at org.jboss.as.weld.services.WeldService.start(WeldService.java:76) ... 5 more
@Inject @Named("userRepo") private UserRepository userRepo;
导致同样的例外.与@Stateful一起工作的唯一的事情是在var声明中使用接口:
@Inject @Named("userRepo") private CachingRepository userRepo;
我可能需要子类功能,所以使用CachingRepository并不是真正需要的(目前).
Q记者:
>为什么这不按预期工作? UserRepository var应该已经识别要实例化的类,不应该吗?这是什么逻辑?
>为什么@Stateful EJB注释在这里有如此严重的影响?为什么它基本上迫使我在var声明中使用CachingRepository接口?
注意,我使用Seam 3 Faces使@ViewScoped成为一个CDI视图范围的bean,所以手头的问题可能仍然是CDI.
解决方法
我有同样的问题,这个误导的例外…
通过将@Stateful添加到UserRepository,您将公开CachingRepository接口的EJB方法,而不声明无接口视图.将@LocalBean添加到UserRepository以激活无界面视图.参见EJB 3.1规范,第4.9.8节“会话Bean的无界面视图”
The bean class must designate that it exposes a no-interface view via its bean class definition or in the deployment descriptor. The following rules apply:
- …
- If the bean exposes at least one other client view,the bean
designates that it exposes a no-interface view by means of the
@LocalBean annotation on the bean class or in the deployment
descriptor.- …
关于无界面视图的更多信息,我也参考this stackoverflow的答案.