Last active
April 9, 2023 15:06
-
-
Save sonus21/aa2263902b10b7907ef3f6adcfe75da9 to your computer and use it in GitHub Desktop.
Database Aspect
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Aspect | |
@Component | |
public class DatabaseAspect { | |
/** | |
* AOP joint point handler that will be invoked by AOP when it encounters a method annotated with Database | |
* or the class containing this method is annotated with Database. | |
* | |
* @param jointPoint joint point object | |
* @return the result of joint point | |
* @throws Throwable if any exception occurred while handling joint point | |
*/ | |
@Around("@within(Database) || @annotation(Database)") | |
public Object database(ProceedingJoinPoint jointPoint) throws Throwable { | |
MethodSignature signature = (MethodSignature) jointPoint.getSignature(); | |
Method method = signature.getMethod(); | |
String name = findDatabaseName(method).orElse(""); | |
try { | |
DatabaseContext.set(name); | |
return jointPoint.proceed(); | |
} finally { | |
DatabaseContext.clear(); | |
} | |
} | |
/** | |
* findDatabaseName finds the database name for this method, the method or class declaring | |
* this method would have Database annotation. We try to first find the annotation from the method | |
* if method does not contain the annotation than we check class if that contains any annotation. | |
* | |
* @param method method object | |
* @return an optional string | |
*/ | |
private Optional<String> findDatabaseName(Method method) { | |
// the performance of this can be improved by caching the result in a map | |
Database database = Optional.ofNullable(method.getAnnotation(Database.class)).orElseGet(() -> { | |
Class<?> klass = method.getDeclaringClass(); | |
return AnnotationUtils.findAnnotation(klass, Database.class); | |
}); | |
return Optional.ofNullable(database).map(Database::value); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment