注解实现切面、枚举
使用注解的方式设置切面
import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; /** * 由于只涉及读写分离,此方法为神农DynamicDataSourceAspect 功能缩减版 */ @Aspect @Order(-10)//保证该AOP在@Transactional之前执行 @Component public class DataSourceRoutingMethodAspect implements ApplicationContextAware { ApplicationContext ac; /* * @Before("@annotation(dynamicDataSource)") * 会拦截注解dynamicDataSource的方法,否则不拦截; */ @Before("@annotation(dataSourceMethod)") public void changeDataSource(JoinPoint point, DataSourceMethod dataSourceMethod) { logger.debug(point.getTarget().getClass().getName()+"."+point.getSignature().getName()+"开始切换数据源"); //获取当前的指定的数据源; String dataSourceName = dataSourceMethod.dataSourceName(); logger.debug(point.getTarget().getClass().getName()+"."+point.getSignature().getName()+"使用数据源["+dataSourceName+"]"); DynamicDataSourceContextHolder.setDataSourceType(dataSourceName); } @After("@annotation(dataSourceMethod)") public void restoreDataSource(JoinPoint point, DataSourceMethod dataSourceMethod) { //方法执行完毕之后,销毁当前数据源信息,进行垃圾回收。 DynamicDataSourceContextHolder.clearDataSourceType(); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.ac = applicationContext; } }
//业务层,添加注解,设置注解里的元数据 设置指定数据源 @DataSourceMethod(dataSourceName="read") public TblAccountStatistic queryAccountStatistic(TblAccountStatistic tblAccountStatistic,String logKey) throws Exception { TblAccountStatistic result = tblAccountStatisticMapper.select(tblAccountStatistic); return result; }
import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface DataSourceMethod { /** * 指定读库或者写库 * @return */ String dataSourceName(); }
枚举的使用:常使用的地方:我们要从另一个函数得到一个值,但是这个值只能够在一个范围内的,此时我们就可以使用枚举来定义这个范围。限制另外一个函数能够传递进来的值,只能够是枚举类型里面的元素
public enum DataSourceName { GCOINREAD("read"),GCOINWRITE("write"); private String name; DataSourceName(String name) { this.name =name; } public String getDataSource() { return this.name; } } public static void main(String[] args) { DataSourceName dn = DataSourceName.GCOINREAD; System.out.println(dn.getDataSource()); } public enum Color{ BULE,RED,GREEN}; public static void main(String[] args) { Color s = Color.BULE; System.out.println(s.toString()); }