基于@AspectJ的AOP

1 基本概念

    在讲解@AspectJ之前,我们先来看一下AOP的几个重要的概念。

1.1 连接点(Joinpoint)

    是指程序执行的某个特定位置,比如类开始初始化前,类初始化后,某个方法调用前,某个方法调用后,或者方法抛出异常后。一个类或一段程序代码拥有一些具有边界性质的特定点,这些代码中的特定点就称为“连接点”。
    Spring仅支持方法级别上的连接点,即方法调用前后和方法抛出异常时。
    连接点包括两个方面的信息:哪个方法以及方法的哪个方位。
    连接点是客观存在的。

1.2 切点(Pointcut)

    AOP首先通过切点信息,过滤连接点,将切面定位到某个方法上。但是至于方法的哪个方位,切点并不负责。

1.3 增强(Advice)

    增强包括两方面信息:(1)一段程序代码,即增强逻辑;(2)方位信息,即方法的前还是后,或者环绕的,或者异常抛出后。

1.4 切面(Aspect)

    切面由切点和增强构成。

1.5 目标对象(Target)

    被代理的对象。

1.6代理(Proxy)

    将增强逻辑织入目标类后,就会得到代理类。

2 代码实现

Person.java
package study.aspectj;

public class Person {
	public void haveDinner() {
		System.out.println("吃晚饭...");
	}
}
PreDinnerAspect.java
package study.aspectj;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class PreDinnerAspect {
	@Before("execution(* haveDinner(..))")
	public void beforeDinner() {
		System.out.println("洗手...");
	}
}
TestAspect.java
package study.aspectj;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestAspect {
	public static void main(String[] args) {
		ApplicationContext context=new ClassPathXmlApplicationContext("knight.xml");
		Person person=(Person) context.getBean("person");
		person.haveDinner();
	}
}
运行结果:
洗手...
吃晚饭...

knight.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:context="http://www.springframework.org/schema/context"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:jee="http://www.springframework.org/schema/jee" 
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd	
	http://www.springframework.org/schema/aop  
    http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-3.0.xsd
	http://www.springframework.org/schema/jee 
	http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
	http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd">
    <aop:aspectj-autoproxy/>
    <bean id="person" class="study.aspectj.Person"/>
    <bean class="study.aspectj.PreDinnerAspect"/>

</beans>






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值