New file |
| | |
| | | package com.dy.common.multiDataSource; |
| | | |
| | | |
| | | import com.dy.common.contant.Constant; |
| | | import com.dy.common.springUtil.SpringContextUtil; |
| | | import com.mysql.cj.util.StringUtils; |
| | | import lombok.extern.slf4j.Slf4j; |
| | | import org.aspectj.lang.ProceedingJoinPoint; |
| | | import org.aspectj.lang.annotation.Around; |
| | | import org.aspectj.lang.annotation.Aspect; |
| | | import org.aspectj.lang.annotation.Pointcut; |
| | | import org.aspectj.lang.reflect.MethodSignature; |
| | | import org.springframework.core.annotation.Order; |
| | | import org.springframework.stereotype.Component; |
| | | |
| | | import java.lang.reflect.Method; |
| | | import java.util.Objects; |
| | | |
| | | @Slf4j |
| | | @Aspect |
| | | @Order(Constant.AspectOrderDataSource) |
| | | @Component |
| | | public class DataSourceSingleAspect { |
| | | |
| | | @Pointcut("@annotation(com.dy.common.multiDataSource.DataSourceSingle)") |
| | | public void dataSourceSinglePointCut() { |
| | | } |
| | | |
| | | @Around("dataSourceSinglePointCut()") |
| | | public Object around(ProceedingJoinPoint point) throws Throwable { |
| | | MethodSignature signature = (MethodSignature) point.getSignature(); |
| | | Method method = signature.getMethod(); |
| | | DataSourceSingle dataSource = method.getAnnotation(DataSourceSingle.class); |
| | | |
| | | if (Objects.nonNull(dataSource) && !StringUtils.isNullOrEmpty(dataSource.value())) { |
| | | //log.info("数据源指定为" + dataSource.value()); |
| | | //强制转成方法上配置的数据源,替换掉DataSourceContext中保存的数据源 |
| | | DataSourceContext.set(dataSource.value()); |
| | | }else{ |
| | | String datasourceName = SpringContextUtil.getApplicationContext().getEnvironment().getProperty("spring.datasource.names") ; |
| | | if(!StringUtils.isNullOrEmpty(datasourceName)){ |
| | | //log.info("根据配置数据源为" + datasourceName); |
| | | DataSourceContext.set(datasourceName); |
| | | }else{ |
| | | log.error("数据源未指定"); |
| | | } |
| | | } |
| | | try { |
| | | //log.info("数据库操作开始" + dataSource.value()); |
| | | return point.proceed(); |
| | | } finally { |
| | | // 销毁数据源 在执行方法之后 |
| | | //log.info("数据源操作完毕" + dataSource.value()); |
| | | DataSourceContext.remove(); |
| | | } |
| | | } |
| | | } |