自己定义的注解:
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
String value();
}
配置文件加载(applicationContext.xml):
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.1.xsd">
com.controller:
@Controller
public class TestController {
@RequestMapping({ "/test.do" }) //方便测试,加了一个访问请求的入口
@MyAnnotation(value = "hello") //这里便是自己添加的注解
public void test(HttpServletRequest request,
HttpServletResponse response) {
System.out.println("test Aspect");
}
}
com.aspect:
@Component
@Aspect
public class ControllerAspect {
@Pointcut("execution(@com.annotation.MyAnnotation * *(..))")
public void controllerPointcut() {}
@Around("controllerPointcut()")
public Object controllerAround(ProceedingJoinPoint joinPoint)
throws Throwable {
// 执行的类
String exeType = null;
// 执行的方法
String exeMethod = null;
long start = System.currentTimeMillis();
try {
// 获取接口的请求参数
MethodSignature signature = (MethodSignature) joinPoint
.getSignature();
exeType = signature.getDeclaringType().getCanonicalName();
exeMethod = signature.getMethod().getName();
System.out.println(exeType + " " + exeMethod);
return joinPoint.proceed();
} catch (Throwable ex) {
} finally {
LOG.info("[{}.{} end,cost {} ms]", new Object[] {
exeType, exeMethod, (System.currentTimeMillis() - start)
});
}
return joinPoint.proceed();
}
}
运行:
http://localhost:8080/Java/test.do
结果:
com.controller.TestController test
test Aspect