基于javaconfig的Spring的面向切面编程

基于javaconfig的Spring的面向切面编程,术语有通知(advice)、切点(pointcut)、和连接点(joinpoint)。
通知:定义了切面是什么以及何时使用,spring有五种通知方式:
1.前置通知before:再目标方法前调用通知
2.后置通知after:在目标方法后调用通知
3.返回通知afterReturn:在目标方法返回后调用通知
4.异常通知afterThrowing:在目标方法异常后调用通知
5.环绕通知arount:在目标方法前后执行逻辑;
切点:就是在何处调用通知,spring是基于方法的面向切面,所以切点就是目标方法;
连接点:就是通知在什么时机调用;
切面:就是通知和切点的结合,即描述了是什么,在何处、何时调用;
示例:

/**
 * AOP方法
 * Created by 15692 on 2019/3/14.
 */
@Aspect
public class AopDemo {

    @Pointcut(value = "execution(* nui.honest.spring.demo.aop.demo.BasePojo.test(..))")
    public void cut() {
    }

    @Before("cut()")
    public void before() {
        System.out.println("Before Test is running");
    }

    @After("cut()")
    public void after() {
        System.out.println("After test() is running");
    }

    @AfterThrowing("cut()")
    public void afteeException() {
        System.out.println("AfterException test() is runnting");
    }

    @AfterReturning("cut()")
    public void afterReturn() {
        System.out.println("AfterReturning test() is running");
    }

    @Around("cut()")
    public void around(ProceedingJoinPoint joinPoint) throws Exception {
        try {
            System.out.println("Around Before test() is running");
            joinPoint.proceed();
            System.out.println("Around after test() is running");
        }catch (Throwable throwable) {
            System.out.println("Around throw Excetption test() is running");
            throw new Exception("arrasdfas");
//            throwable.printStackTrace();
        }
    }
}

/**
 * 目标方法
 * Created by 15692 on 2019/3/14.
 */
@Component
public class BasePojo {
    public void test() throws Exception {
        System.out.println("AOP Test POJO");
        throw new Exception("Exception throwed");
    }
}

/**
 * 配置
 * Created by 15692 on 2019/3/14.
 */
@ComponentScan(value={"nui.honest.spring.demo.aop"})
@Configuration
@EnableAspectJAutoProxy
public class DemoConfig {

    @Bean
    public AopDemo aopDemo() {
        return new AopDemo();
    }
}
/**
 * junit测试
 * Created by 15692 on 2019/3/14.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = DemoConfig.class)
public class AOPDemoTest {
    @Autowired
    private BasePojo basePojo;

    @Test
    public void aopDemoTest()  {
        try {
            basePojo.test();
        } catch (Exception e) {
            System.out.println("i am error");
        }
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值