SpringBoot @DS注解实现多数据源配置及问题解决
    		       		warning:
    		            这篇文章距离上次修改已过429天,其中的内容可能已经有所变动。
    		        
        		                
                
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DS {
    String value() default "master"; // 默认数据源
}
 
// 使用@DS注解选择数据源
@Service
public class DataSourceService {
 
    public DataSourceType getDataSourceType(DS dsAnnotation) {
        return DataSourceType.valueOf(dsAnnotation.value()); // 获取注解中定义的数据源类型
    }
 
    public DataSourceType getDataSourceType(ProceedingJoinPoint pjp) throws NoSuchMethodException {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
 
        DS dsAnnotation = method.getAnnotation(DS.class);
        if (dsAnnotation != null) {
            return getDataSourceType(dsAnnotation);
        }
 
        // 如果方法上没有@DS注解,则查找类上的@DS注解
        dsAnnotation = pjp.getTarget().getClass().getAnnotation(DS.class);
        if (dsAnnotation != null) {
            return getDataSourceType(dsAnnotation);
        }
 
        return null; // 如果没有找到@DS注解,则返回null
    }
 
    // 其他方法...
}这个代码示例展示了如何定义@DS注解,并在服务类中使用该注解来确定使用哪个数据源。它提供了一个简单的方法来获取注解中定义的数据源类型。如果方法或类上没有找到@DS注解,则返回null。这个简单的逻辑可以根据实际项目的需要进行扩展和优化。
评论已关闭