自定义注解:
package aop;
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;
/*指定注解修饰元素*/
@Target({ElementType.METHOD})
/*运行时保留*/
@Retention(RetentionPolicy.RUNTIME)
/*文档保留*/
@Documented
public @interface MyAnnotation {
/**
* 测试自定义注释
* @return
*/
String method() default "";
}
aop目标类:
package aop;
public class Target {
/**
* 存储方法
*/
@MyAnnotation(method = "测试注解")
public void save() {
System.out.println("save方法执行");
}
}
aop通知类:
package aop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
/*该类时通知类*/
@Aspect
public class Myadvice {
/**
* 声明切入点
*/
@Pointcut(value = "execution(* aop.Target.save(..))")
public void pc() {
}
/**
* 环绕通知
*
* @throws Throwable
*/
@Around("Myadvice.pc()&&@annotation(mytest)")
public Object aroundMethod(ProceedingJoinPoint pjp, MyAnnotation mytest) throws Throwable {
System.out.println("环绕通知前*********************");
System.out.println(mytest.method() + "*********************8");
Object tagert = pjp.proceed();
System.out.println("环绕通知后*********************");
return tagert;
}
}
测试类:
package aop;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath*:applicationContext.xml")
public class test {
@Resource(name="daoImpl")
Target dao;
@Test
public void saveTest() {
dao.save();
}
}
applicationContest.xml配置:
<?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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- bean definitions here -->
<!-- 1.配置目标对象 -->
<bean id="daoImpl" class="aop.Target" />
<!-- 2.配置通知对象 -->
<bean id="myaspectj" class="aop.Myadvice" />
<!-- 3.开启使用注解完成织入 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
参考:https://blog.csdn.net/qpfjalzm123/article/details/45061701