自定义注解aop业务实现
例如定义一个自定义注解
- @Target({ElementType.METHOD, ElementType.TYPE})
- @Retention(RetentionPolicy.RUNTIME)
- @Documented
- public @interface Test {
- String value();
}
这个时候我们的注解就已经搞定了,接下来就是实现他的业务逻辑了。而实现他的业务是以aop的方式去实现的。
在实现之前我们先去了解一下几个aop常用的注解
aop常用的注解
1、@Aspect作用是把当前类标识为一个切面供容器读取
2、@before标识一个前置增强方法,相当于BeforeAdvice的功能
3、@after final增强,不管是抛出异常或者正常退出都会执行
4、@Pointcut定义切点
5、@Around
- @Aspect
- @Component
- public class OperateAspect {
- @Pointcut("@annotation(com.junge.annotation.Test)")
- public void annotationPointCut() {
- }
- //
- @Before("annotationPointCut()")
- public void before(JoinPoint joinPoint){
- MethodSignature sign = (MethodSignature)joinPoint.getSignature();
- Method method = sign.getMethod();
- Test annotation = method.getAnnotation(Test.class);
- System.out.print("打印:"+annotation.value()+" 开始前");
- }
- @Around("annotationPointCut()")
- public Object advice(ProceedingJoinPoint joinPoint){
- System.out.println("通知之开始");
- Object retmsg=null;
- try {
- retmsg=joinPoint.proceed();
- System.err.println("++++++++"+retmsg);
- } catch (Throwable e) {
- e.printStackTrace();
- }
- System.out.println("通知之结束");
- return retmsg;
- }
- @After("annotationPointCut()")
- public void after() {
- System.out.println("after方法执行后");
- }
}
这样就实现了一个简单的自定义注解,如果你有自己的业务要写的话,你可以在某个方法里面写你的业务,比如记录操作日志,那么你就可以在@after方法里面写你的业务层代码。
然后在你的接口上面可以加上@Test注解
- */
- @SpringBootApplication
- @RestController
- @EnableAspectJAutoProxy
- public class App
- {
- public static void main( String[] args )
- {
- // System.out.println( "Hello World!" );
- SpringApplication.run(App.class, args);
- }
- @RequestMapping("/")
- @Test("测试")
- public List<String> getById() {
- // haha();
- System.err.println("o+++++++++++++++++");
- List<String> list=new ArrayList<String>();
- list.add("1");
- list.add("qwe");
- list.add("asd");
- return list;
- }

浙公网安备 33010602011771号