spring对AOP的支持(采用Annotation的方式)
支持库:/lib/aspectj/aspectjrt.jar和aspectjweaver.jar
UserManagerImpl类:
package com.jzq.spring;
public class UserManagerImpl implements UserManager {
@Override
public void addUser(String username, String password) {
System.out.println("------UserManagerImpl.addUser()-----");
}
@Override
public void deleteUser(int id) {
System.out.println("--------UserManagerImpl.deleteUser()-------");
}
@Override
public String findUserById(int id) {
System.out.println("--------UserManagerImpl.findUser()----------");
return null;
}
@Override
public void modifyUser(int id, String username, String password) {
System.out.println("--------deleteUser()-------");
}
}
切面类:
package com.jzq.spring;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
/**
* 定义切面Aspect
* @author Administrator
*
*/
@Aspect
public class SecurityHandler {
/**
* 定义Pointcut,Pointcut的名称就是allAddMethod
* 此方法不能有返回值和参数,该方法只是一个标识
*
* Pointcut的内容是一个表达式,描述了哪些对象的
* 哪些方法使用(订阅Joinpoint),切入点的方法是一个标识不被执行
*/
@Pointcut("execution(* add*(..))")
private void allAddMethod(){};
/**
* 定义Advice,标识在哪个切入点何处织入此方法
*
*/
@Before("allAddMethod()")
private void checkSecurity()
{
System.out.println("---------checkSecurity()------------");
}
}
配置文件:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
<!-- 启用注释-->
<aop:aspectj-autoproxy/>
<bean id="securityHandler" class="com.jzq.spring.SecurityHandler"/>
<bean id="userManager" class="com.jzq.spring.UserManagerImpl"/>
</beans>
客户端:
package com.jzq.spring;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Client {
public static void main(String args[])
{
BeanFactory factory=new ClassPathXmlApplicationContext("applicationContext.xml");
UserManager userManager=(UserManager)factory.getBean("userManager");
}
}