注意:在花费了比我想承认的更多的时间来寻找原因之后,以简短的形式添加这个问题并给出答案。希望我能减轻别人的痛苦。
将方法调用委托给带有EJB
注释的方法时@Singleton
,容器会抛出异常,如下所示:
TransactionRolledbackLocalException Client's transaction aborted
Singleton bean 没有发生数据访问。
ServiceBeanImpl.java
@Stateless
@Local
public class ServiceBean extends BaseBean{
@EJB private CacheService cacheService;
public FooObj getFooFromCache(int id) {
FooObj fooObj = (FooObj) cacheService.get(id);
if (fooObj == null) {
fooObj = getEntityById(FooObj.class, id);
cacheService.put(id, fooObj); //This throws exception
}
return cacheService.get(id);
}
}
CacheServiceImpl.java
@Singleton
@Startup
public class CacheServiceImpl implements CacheService {
private Cache cache;
@PostConstruct
public void init() {
CacheManager instance = CacheManager.getInstance();
cache = instance.getCache("cache");
}
@PreDestroy
public void destroy() {
CacheManager.getInstance().shutdown();
}
public Object get(Object id) {
return cache.get(id);
}
public void put(Object id, Object obj) {
return cache.put(id, obj);
}
}
问题 为什么调用没有数据访问的 Singleton bean 会引发 Transaction 异常?