Spring AOP

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的情况下

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值