001/** 002 * Copyright (c) 2015-2022, Michael Yang 杨福海 (fuhai999@gmail.com). 003 * <p> 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * <p> 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * <p> 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package io.jboot.db.datasource; 017 018import com.jfinal.aop.Interceptor; 019import com.jfinal.aop.Invocation; 020import io.jboot.aop.InterceptorBuilder; 021import io.jboot.aop.Interceptors; 022import io.jboot.aop.annotation.AutoLoad; 023import io.jboot.db.JbootDb; 024import io.jboot.db.annotation.PriorDatasource; 025import io.jboot.utils.AnnotationUtil; 026import io.jboot.utils.StrUtil; 027 028import java.lang.reflect.Method; 029 030/** 031 * @author Michael Yang 杨福海 (fuhai999@gmail.com) 032 */ 033@AutoLoad 034public class PriorDatasourceInterceptor implements Interceptor, InterceptorBuilder { 035 036 037 @Override 038 public void intercept(Invocation inv) { 039 PriorDatasource datasource = getAnnotation(inv); 040 if (datasource != null) { 041 String configName = AnnotationUtil.get(datasource.value()); 042 if (StrUtil.isNotBlank(configName)) { 043 JbootDb.setCurrentConfigName(configName); 044 } 045 } 046 047 inv.invoke(); 048 } 049 050 051 052 private PriorDatasource getAnnotation(Invocation inv) { 053 PriorDatasource annotation = inv.getController().getClass().getAnnotation(PriorDatasource.class); 054 return annotation != null ? annotation : inv.getMethod().getAnnotation(PriorDatasource.class); 055 } 056 057 058 059 @Override 060 public void build(Class<?> targetClass, Method method, Interceptors interceptors) { 061 if (Util.hasAnnotation(targetClass, PriorDatasource.class) || Util.hasAnnotation(method, PriorDatasource.class)) { 062 interceptors.add(this); 063 } 064 } 065}