Spring AOP
目标类
public interface DService {
public void add();
public void delete();
}
目标子类
import org.springframework.stereotype.Service;
@Service(“serviceId”)
public class DServiceImpl implements DService {
@Override
public void add() {
// TODO Auto-generated method stub
System.out.println("2 add");
}
@Override
public void delete() {
// TODO Auto-generated method stub
System.out.println("2 delete");
}
}
切面类
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
/**
* 切面类,含有多个通知
*/
@Component
@Aspect
public class PdAspect {
//切入点当前有效
// @Before(“execution(* com.formssi.aspect.b_anno.DServiceImpl.*(..))”)
public void pdBefore(JoinPoint joinPoint){
System.out.println(“前置通知 : ” + joinPoint.getSignature().getName());
}
//声明公共切入点
@Pointcut("execution(* com.formssi.aspect.b_anno.DServiceImpl.*(..))")
private void pdPointCut(){
}
// @AfterReturning(value=”pdPointCut()” ,returning=”ret”)
public void pdAfterReturning(JoinPoint joinPoint,Object ret){
System.out.println(“后置通知 : ” + joinPoint.getSignature().getName() + ” , –>” + ret);
}
// @Around(value = “pdPointCut()”)
public Object pdAround(ProceedingJoinPoint joinPoint) throws Throwable{
System.out.println(“前”);
//手动执行目标方法
Object obj = joinPoint.proceed();
System.out.println("后");
return obj;
}
// @AfterThrowing(value=”execution(* com.formssi.aspect.b_anno.DServiceImpl.*(..))” ,throwing=”e”)
public void pdAfterThrowing(JoinPoint joinPoint,Throwable e){
System.out.println(“抛出异常通知 : ” + e.getMessage());
}
@After("pdPointCut()")
public void pdAfter(JoinPoint joinPoint){
System.out.println("最终通知");
}
}
配置文件
1.扫描 注解类
context:component-scan base-package=”com.formssi.aspect.b_anno”>/context:component-scan>
2.确定 aop注解生效
aop:aspectj-autoproxy>
ps: 此处少了一些括号
测试
@org.junit.Test
public void test() {
String xmlPath = "com/formssi/aspect/b_anno/beans.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
//获得目标类
DService userService = (DService) applicationContext.getBean("serviceId");
userService.add();
userService.delete();
}
特别注意
org.springframework.beans.factory.BeanDefinitionStoreException: Failed to read candidate component class: file [D:\workplace\JavaEE\Pdspring\bin\com\formssi\aspect\b_anno\DService.class]; nested exception is java.lang.IllegalArgumentException
此错误,很可能是因为Spring的jar包需要导入4.3版本的在jdk1.8的情况下