Transactor函数式编程启动事务
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.function.Supplier;
@Component("myTransactor")
public class Transactor {
private final static Logger LOGGER = LoggerFactory.getLogger(Transactor.class);
private static Transactor instance;
public static Transactor getInstance() {
if (instance == null) {
try {
instance = (Transactor) SpringContextHolder.getBean("myTransactor");
} catch (Exception e) {
LOGGER.error("获取Transactor对象异常:", e);
}
}
return instance;
}
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = java.lang.Exception.class)
public <R> R getThrowsException(SupplierThrowException<R> f) throws Exception {
return f.get();
}
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = java.lang.Exception.class)
public <R> R get(Supplier<R> f) {
return f.get();
}
@Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = java.lang.Exception.class)
public <R> R getRequiredNewThrowsException(SupplierThrowException<R> f) throws Exception {
return f.get();
}
@Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = java.lang.Exception.class)
public <R> R getRequiredNew(Supplier<R> f) {
return f.get();
}
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = java.lang.Exception.class)
public void run(Runnable f) {
f.run();
}
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = java.lang.Exception.class)
public void runThrowsException(RunnableThrowException f) throws Exception {
f.run();
}
@Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = java.lang.Exception.class)
public void runRequiredNew(Runnable f) {
f.run();
}
@Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = java.lang.Exception.class)
public void runRequiredNewThrowsException(RunnableThrowException f) throws Exception {
f.run();
}
}
@FunctionalInterface
public interface RunnableThrowException {
void run() throws Exception;
}