我的项目使用模板服务模式。
我尝试了两种方法。
一,使用@autowired annotation.然后,设置我的参数。
二,使用AutowireCapableBeanFactory。在程序上创建ServiceTemplate,然后用autowireBean。
我的服务模板类是
public class ServiceTemplate<T>{
public ServiceTemplate(){}
public ServiceTmeplate(T clazz, ...){
...}
@Transactional
public Response someMethod(){
try{
...}
catch{
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
}
在我的控制器上的代码是
@Autowired
private AutowireCapableBeanFactory beanfactory
public Resonse getTest(){
final ServiceTemplate<testClass> serviceTemplate = new ServiceTemplate<>(.....)
beanfactory.autowireBean(seviceTemplate)
}
在我的第一个方法,它的工作。就是回滚所有的交易。
但我想采用第二种方法。如何让我的Bean在事务管理器下编程。
第二种方法不能用,因为你的 ServiceTemplate
是自管理的,所以Spring不能代理你的Bean的事务性问题。这里只有依赖关系是由Spring管理和自动装配的。
一个解决方案是使用程序化的事务
class ServiceTemplate {
@Autowired
private PlatformTransactionManager transactionManager;
private TransactionTemplate transactionTemplate;
public Response someMethod() {
//
transactionTemplate.execute(status ->
{
// the code in this method executes in a transactional context
}
});
//
}