Created
June 19, 2013 13:40
-
-
Save nyilmaz/5814411 to your computer and use it in GitHub Desktop.
InMemoryAspect
This file contains 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
package pipe.plug.inmemory; | |
import com.google.common.base.CaseFormat; | |
import org.aspectj.lang.ProceedingJoinPoint; | |
import org.aspectj.lang.annotation.Around; | |
import org.aspectj.lang.annotation.Aspect; | |
import org.aspectj.lang.reflect.MethodSignature; | |
import org.slf4j.Logger; | |
import org.slf4j.LoggerFactory; | |
import org.springframework.beans.factory.NoSuchBeanDefinitionException; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.context.ApplicationContext; | |
import org.springframework.stereotype.Component; | |
import java.lang.reflect.InvocationTargetException; | |
import java.lang.reflect.Method; | |
/** | |
* @author nyilmaz | |
*/ | |
@Aspect | |
@Component | |
public class InMemoryAdvice { | |
private static final Logger logger = LoggerFactory.getLogger(InMemoryAdvice.class); | |
@Autowired | |
ApplicationContext applicationContext; | |
public InMemoryAdvice(){} | |
@Around("@annotation(valAnno)") | |
public Object check(ProceedingJoinPoint joinPoint, InMemory valAnno){ | |
try { | |
String implementedIFaceName = joinPoint.getTarget().getClass().getSimpleName().replace("Impl", ""); | |
String alternateImplName = implementedIFaceName.concat("InMemoryImpl"); | |
Object[] args = joinPoint.getArgs(); | |
Class<?>[] argsTypes = ((MethodSignature)joinPoint.getSignature()).getParameterTypes(); | |
String methodName = joinPoint.getSignature().getName(); | |
Object alternateBean = applicationContext.getBean(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, alternateImplName)); | |
Class<?> alternateBeanClass = alternateBean.getClass(); | |
Method alternateMethod = alternateBeanClass.getMethod(methodName, argsTypes); | |
return alternateMethod.invoke(alternateBean, args); | |
} catch(NoSuchBeanDefinitionException e){ | |
logger.error("No bean definition found. Proceeding..." + e.getMessage()); | |
} catch(InvocationTargetException e) { | |
logger.error("Cannot call method.", e); | |
} catch(NoSuchMethodException e) { | |
logger.error("No such method.", e); | |
} catch(IllegalAccessException e) { | |
logger.error("Cannot access method, check modifiers.", e); | |
} finally { | |
try { | |
joinPoint.proceed(); | |
} catch(Throwable throwable) { | |
logger.error("Error while proceeding.", throwable); | |
} | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment