Skip to content

Instantly share code, notes, and snippets.

@sonus21
Last active April 9, 2023 15:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sonus21/aa2263902b10b7907ef3f6adcfe75da9 to your computer and use it in GitHub Desktop.
Save sonus21/aa2263902b10b7907ef3f6adcfe75da9 to your computer and use it in GitHub Desktop.
Database Aspect
@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