您的位置:首页 > 编程语言 > ASP

spring中利用aspectJ自定义注解

2017-11-01 04:02 183 查看
1.spring配置文件开启aspect切面

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd"> <aop:aspectj-autoproxy />
<!--配置切面-->
<context:component-scan base-package="wjf.maven">
<context:include-filter type="annotation"
expression="org.aspectj.lang.annotation.Aspect" />
</context:component-scan>
<!--配置扫描包-->
</beans>


2.自定义注解

package wjf.maven;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.PARAMETER })
public @interface DemoAnnotation {
//定义注解里的参数,通过default指定默认值
String desc() default "##########无描述信息##########";
}


3.实现
4000
该注解的功能


package wjf.maven;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

//定义一个切面
@Aspect
public class DemoProcess {

@Around(value = "execution(* wjf.maven.*.*(..)) && @annotation(log)")
public Object aroundMethod(ProceedingJoinPoint pjd, DemoAnnotation log ) {
Object result = null;
System.out.println(log.desc());//拿到注解后的参数
try {
System.out.println("前置通知");
result = pjd.proceed();
System.out.println("后置通知");
} catch (Throwable e) {
System.out.println("异常通知");
}
System.out.println("返回通知");
return result;
}
}


4.测试结果

package wjf.maven;

import org.springframework.stereotype.Service;

@Service
public class AopTest {
@DemoAnnotation(desc = "我是测试")
public void test() {
// System.out.println("hello world!!");
}

@DemoAnnotation
public void test2() {
System.out.println("hello world!!");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: