-
创建目标接口和目标类(内部有切点)
创建com.zcl.anno
包,将上面aop
包里的接口和类复制过来
-
创建切面类(内部有增强方法)
请看复制的MyAspect
类
-
将目标类和切面类的对象创建权交给spring
使用@Component("target")
package com.zcl.anno;
import org.springframework.stereotype.Component;
@Component("traget")
public class Traget implements TargetInterface {
@Override
public void save() {
System.out.println("save running....");
}
}
同理在MyAspect
切面类中也需要通过@Component("myAspect")
完成注解快发
同时在NyAspect
类的上面还需要加上@Aspect
标注当前MyAspect是一个切面类
-
在切面类中使用注解配置织入关系
通过@Before()
方式配置
package com.zcl.anno;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Component("myAspect")
@Aspect
public class MyAspect {
@Before("execution(* com.zcl.anno.*.*(..))")
public void before(){
System.out.println("前置增强....");
}
public void afterReturning(){
System.out.println("后置增强....");
}
public Object around(ProceedingJoinPoint pjpt) throws Throwable {
System.out.println("环绕前增强....");
Object proceed = pjpt.proceed();
System.out.println("环绕后增强....");
return proceed;
}
public void afterThroewing(){
System.out.println("异常抛出增强....");
}
public void after(){
System.out.println("最终增强....");
}
}
-
在配置文件中开启组件扫描和AOP的自动代理
在resources
包下创建applictionContext-anno.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"
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/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
">
<context:component-scan base-package="com.zcl.anno"/>
<aop:aspectj-autoproxy/>
</beans>
如果没有aop自动代理
就无法识别注解的@Aspect
和@Before
-
测试
在test
包下的com.zcl.test
下创建AnnoTest
注解测试类
package com.zcl.test;
import com.zcl.anno.TargetInterface;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applictionContext-anno.xml")
public class AnnoTest {
@Autowired
public TargetInterface target;
@Test
public void test1(){
target.save();
}
}
因为是复制过来的类和就接口,需要检查是否对上当前的anno
包,否则会出现找包异常报错