资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

springmvc无法支持事务控制如何解决

这篇文章将为大家详细讲解有关spring mvc无法支持事务控制如何解决,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

成都网站建设哪家好,找创新互联公司!专注于网页设计、成都网站建设公司、微信开发、小程序开发、集团企业网站设计等服务项目。核心团队均拥有互联网行业多年经验,服务众多知名企业客户;涵盖的客户类型包括:纱窗等众多领域,积累了大量丰富的经验,同时也获得了客户的一致赞扬!

spring-mybatis.xml 配置


  
   
    classpath:spring/db.properties
   
  
  
 

 
  
  
  
  

  
  
  
  
  
 


 
 
  
  
  
  

  
  
  
  
  
  
  
  

  
  
  
  

  
  
  
  

  
  
  
  
  
  

  
  
 


 
  
  
   
    
    
   
  
 

 
 
  
  
  
 

 
  
  
 


 
 
  
 

 
 


 
 
  
   
  
 

 
 

 
  
  

  
  
 

注解切换,默认使用oracle数据源

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.TYPE})

public @interface DataSource {
  String name() default DataSource.oracleDataSource;
  String mySqlDataSource = "mySqlDataSource";
  String oracleDataSource = "oracleDataSource";
}

注解方式实现切换数据源,搜索注释,更换注释上面的数据源,支持类注释和方法注释

/**
 * Created by eastday on 2017/9/21.
 */
public class DataSourceAspect implements MethodBeforeAdvice,AfterReturningAdvice
{

 @Override
 public void afterReturning(Object returnValue, Method method,
        Object[] args, Object target) throws Throwable {

  MultipleDataSource.clearDataSource();
 }

 @Override
 public void before(Method method, Object[] args, Object target)
   throws Throwable {

  //首先取类上的数据源
  if(method.getDeclaringClass().isAnnotationPresent(DataSource.class) && !method.isAnnotationPresent(DataSource.class)) {

   DataSource datasource = method.getDeclaringClass().getAnnotation(DataSource.class);
   MultipleDataSource.setDataSource(datasource.name());

   //方法上的数据源 优先级高于类上的
  } else if (method.isAnnotationPresent(DataSource.class)) {

   DataSource datasource = method.getAnnotation(DataSource.class);
   MultipleDataSource.setDataSource(datasource.name());
  }
  else
  {
   MultipleDataSource.setDataSource(DataSource.oracleDataSource);
  }
 }
}

继承AbstractRoutingDataSource实现数据源切换

public class MultipleDataSource extends AbstractRoutingDataSource {
 private static final ThreadLocal dataSources = new InheritableThreadLocal();

 public static void setDataSource(String dataSource) {
  dataSources.set(dataSource);
 }

 //清除数据源
 public static void clearDataSource() {
  dataSources.remove();
 }

 @Override
 protected Object determineCurrentLookupKey() {
  return dataSources.get();
 }
}

使用demo

@DataSource(name = DataSource.mySqlDataSource)
public class ContentServiceImpl implements IContentService {

 @Autowired
 private IContentDao contentDao;

 @Override
 public Content queryOne(String type) {
  return contentDao.queryOne(type);
 }
}

关于spring mvc无法支持事务控制如何解决就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。


当前标题:springmvc无法支持事务控制如何解决
本文路径:http://cdkjz.cn/article/iejgds.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220