1、什么是@AspectJ:
@AspectJ是采用注解方法来描述切点、增强,两者只是表述的方式不同,描述的内容的本质是完全相同的,这好比一个用中文描述简爱,一个用英文描述简爱
2、@AspectJ语法基础:
Spring支持9个@AspectJ切点表达式函数,他们用不同的方式描述目标类的连接点,根据描述的对象的不同,可以分为4类:
方法切点函数:通过描述目标类方法惺惺定义连接点;
方法入参切点函数:通过描述目标类方法入参的信息定义连接点;
目标类切点函数:通过描述目标类型信息定义连接点;
代理类切点函数:通过描述目标类的代理的信息定义连接点。
3、案例演示:
package com.liu.smart;
/**
* 服务员的接口类
* @author 夏日花语
*/
public interface Waiter {
public void greetTo(String name);
public void serveTo(String name);
}
---------------------------------
package com.liu.smart.impl;
import com.liu.smart.Waiter;
public class NativeWaiter implements Waiter {
@Override
public void greetTo(String name) {
System.out.println("greet To "+name);
}
@Override
public void serveTo(String name) {
System.out.println("serve To "+name);
}
}
---------------------------------
package com.liu.aspect;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
/**
* 使用AspectJ 注解方法定义一个切面
* @author 夏日花语
*/
@Aspect //通过该注解将PreGreetingAspect 标识为一个切面
public class PreGreetingAspect {
//@Before("execution(* greetTo(..))") //定义 切点和增强类型
@Before("execution(* com.liu.smart.impl.NativeWaiter.*(*))")
public void beforeGreetAspect(){ //增强的横切面逻辑
System.out.println("你好,亲爱的顾客.......");
}
}
---------------------------------
<bean id="waiter" class="com.liu.smart.Waiter"></bean>
<bean class="com.liu.smart.impl.NativeWaiter"></bean>
<bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator"></bean>
---------------------------------
package com.liu.action;
import org.springframework.aop.aspectj.annotation.AspectJProxyFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.liu.aspect.PreGreetingAspect;
import com.liu.smart.Waiter;
import com.liu.smart.impl.NativeWaiter;
/**
* 测试类
* @author 夏日花语
*
*/
public class AspectJTest {
public static void main(String[] args) {
//test_01();
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Waiter waiter = (Waiter) context.getBean("waiter");
waiter.greetTo("夏日话语");
}
private static void test_01() {
Waiter target = new NativeWaiter();
AspectJProxyFactory factory = new AspectJProxyFactory();
//设置代理的目标对象
factory.setTarget(target);
//添加切面类型
factory.addAspect(PreGreetingAspect.class);
//生成织入切面的代理对象
Waiter waiter = factory.getProxy();
waiter.greetTo("夏日花语");
waiter.serveTo("夏日花语");
}
}