背景:
改造老項目,須要加一個aop來攔截所的web Controller請求做一些處理,由于老項目比較多,且包的命名也不統(tǒng)一尊搬,又不想每個項目都copy一份相同的代碼,這樣會導致后以后升級很麻煩土涝,不利于維護佛寿。于是我們想做成一個統(tǒng)一的jar包來給各項目引用,這樣每個項目只須要引用該jar但壮,然后配置對應的切面值就可以了冀泻。
我們都知道,java中的注解里面的值都是一個常量蜡饵,
如:@Pointcut("execution(* com.demo.Serviceable+.*(..))")
這種方式原則上是沒有辦法可以進行改變的弹渔。但是我們又要實現(xiàn)這將aop中的切面值做成一個動態(tài)配置的,每個項目的值的都不一樣的溯祸,該怎么辦呢肢专?
首先,我們可以先創(chuàng)建一個類來實現(xiàn) MethodInterceptor 類 :
class LogAdvice implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
System.out.println("Before method");//這里做你的before操作
Object result = invocation.proceed();
System.out.println("After method");//這里做你的after操作
return result;
}
}
然后創(chuàng)建一個Configuration類您没,創(chuàng)建Bean:
@Configuration
public class ConfigurableAdvisorConfig {
@Value("${pointcut.property}")
private String pointcut;
@Bean
public AspectJExpressionPointcutAdvisor configurabledvisor() {
AspectJExpressionPointcutAdvisor advisor = new AspectJExpressionPointcutAdvisor();
advisor.setExpression(pointcut);
advisor.setAdvice(new LogAdvice ());
return advisor;
}
}
這里面的 pointcut.property值來自于你的application.properties 等配置文件鸟召。
這樣,各項目只須要引用該jar氨鹏,然后在配置文件中指定要攔截的pointcut就可以了。