spring对AOP的支持(采用Annotation的方式)
1、spring依赖库
* SPRING_HOME/dist/spring.jar
* SPRING_HOME/lib/commons-logging.jar
* SPRING_HOME/lib/log4j-1.2.14.jar
* SPRING_HOME/lib/*.jar
2、模块化横切关注点,采用@Aspect定义切面
3、在Aspect中定义Pointcut和Advice
4、启用AspectJ对Annotation的支持,参见applicationContext.xml
注意:采用Annotation定义Pointcut,Pointcut的方法是不被执行的,它存在的目的
仅仅是为了Adivce重用Pointcut的定义
AOP中的术语:
* Cross cutting concern
* Aspect
* Advice
* Pointcut
* Jointpoint
* Weave
* target Object
* Proxy
* Introduction
public class Client {
public static void main(String[] args) {
BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");
//必须是接口实现
UserManager userManager = (UserManager)factory.getBean("userManager");
//UserManagerImpl userManager = (UserManagerImpl)factory.getBean("userManager");
userManager.addUser("Tom", "123");
}
}
<aop:aspectj-autoproxy/>
<bean id="securityHandler" class="com.bjsxt.spring.SecurityHandler"/>
<bean id="userManager" class="com.bjsxt.spring.UserManagerImpl"/>
@Aspect
public class SecurityHandler {
/**
* 定义Pointcut,Pointcut的名是allAddMethod,不能有返回值,该方法只是一个标识
* Pointcut内容是一个表达式,来描述织入到哪些对象上的哪些方法(订阅感兴趣Joinpoint)
*/
@Pointcut("execution(* add*(..))")
private void allAddMethod(){}
/**
* 定义Advice,标识在目标对象上的哪些方法织入Advice
*/
@Before("allAddMethod()")
private void checkSecurity() {
System.out.println("-----checkSecurity-------");
}
}
----------------------------
spring对AOP的支持(采用静态配置文件的方式)
1、spring依赖库
* SPRING_HOME/dist/spring.jar
* SPRING_HOME/lib/commons-logging.jar
* SPRING_HOME/lib/log4j-1.2.14.jar
* SPRING_HOME/lib/*.jar
2、配置方法
<aop:config>
<aop:aspect id="securityAspect" ref="securityHandler">
<aop:pointcut id="allAddMethod" expression="execution(* com.bjsxt.spring.*.add*(..)) || execution(* com.bjsxt.spring.*.del*(..))"/>
<aop:before pointcut-ref="allAddMethod" method="checkSecurity"/>
</aop:aspect>
</aop:config>
--------------------------------
spring对AOP的支持
Aspect类默认情况下不需要实现接口,但是对于目标对象(UserManagerImpl.java),默认情况下
必须实现接口,如果没有实现接口必须使用CGLIB库实现代理
我们可以通过在Advice中添加一个JoinPoint参数,这只值是spring自动传入的,从JoinPoint中
我们可以得到相关的参数值,方法名等等
-------------------------
spring对AOP的支持
1、如果目标对象实现了接口,默认会采用JDK的动态代理机制实现AOP
2、如果目标对象实现了接口,可以强制使用CGLIB实现AOP
3、如果目标对象没有实现接口,必须使用CGLIB生成代理,spring会自动在CGLIB和JDK动态代理之间切换
如何强制使用CGLIB生成代理?
* 添加CGLIB库,SPRING_HOME/lib/cglib/*.jar
* 在spring的配置文件中加入:
<aop:aspectj-autoproxy proxy-target-class="true"/>
JDK代理和CGLIB代理的区别?
* JDK代理只能对实现了接口的类生成代理,而不能针对类
* CGLIB是针对类实现代理的,主要对指定的类生成一个子类,并覆盖其中的方法,
因为是继承,所以不能使用final来修饰类或方法
---