【发布时间】:2022-01-23 11:45:33
【问题描述】:
我已阅读 CDI 2.0 规范 (JSR 365) 并发现存在 @Observes(during=AFTER_SUCCESS) 注释,但它实际上需要定义自定义事件才能工作。
这就是我所拥有的:
//simple """transactional""" file system manager using command pattern
@Transactional(value = Transactional.TxType.REQUIRED)
@TransactionScoped
@Stateful
public class TransactionalFileSystemManager implements SessionSynchronization {
private final Deque<Command> commands = new ArrayDeque<>();
public void createFile(InputStream content, Path path, String name) throws IOException {
CreateFile command = CreateFile.execute(content, path, name);
commands.addLast(command);
}
public void deleteFile(Path path) throws IOException {
DeleteFile command = DeleteFile.execute(path);
commands.addLast(command);
}
private void commit() throws IOException{
for(Command c : commands){
c.confirm();
}
}
private void rollback() throws IOException{
Iterator<Command> it = commands.descendingIterator();
while (it.hasNext()) {
Command c = it.next();
c.undo();
}
}
@Override
public void afterBegin() throws EJBException{
}
@Override
public void beforeCompletion() throws EJBException{
}
@Override
public void afterCompletion(boolean commitSucceeded) throws EJBException{
if(commitSucceeded){
try {
commit();
} catch (IOException e) {
throw new EJBException(e);
}
}
else {
try {
rollback();
} catch (IOException e) {
throw new EJBException(e);
}
}
}
}
但是,我想采用仅限 CDI 的解决方案,因此我需要删除任何与 EJB 相关的内容(包括 SessionSynchronization 接口)。如何使用 CDI 获得相同的结果?
【问题讨论】:
标签: java jakarta-ee ejb cdi jta