日期:2014-05-17 浏览次数:21052 次
1、切面类定义
?
package login.aop; import org.aspectj.lang.JoinPoint; public class AspectTest { //该方法中可加参数也可不加,如果加了第一个时切入点 public void before(JoinPoint joinPoint){ //获得拦截的类 String className = joinPoint.getClass().getName(); //获得拦截的方法 String methodName = joinPoint.getSignature().getName(); //joinPoint.getSourceLocation(). System.out.println("before-----------"+className+" "+methodName); } public void after(){ System.out.println("after-----------"); } }
?
?2、配置bean.xml
?
<bean id="userAdvice" class="login.aop.AspectTest"> </bean> <aop:config> <aop:aspect id="userAspect" ref="userAdvice"> <aop:pointcut id="myMethod" expression="execution(public * login.service.impl.*.*(..))" /> <aop:before method="before" pointcut-ref="myMethod"/> <aop:after-returning method="after" pointcut-ref="myMethod"/> </aop:aspect> </aop:config>
?
expression是匹配的方法特征,aop:before/after-returning必须与定义的切面类中的方法名一致, 注意xml的命名空间引用
?
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd" >
?3、测试类
package login.test; import login.service.UserService; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MyAsp { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub ApplicationContext context = new ClassPathXmlApplicationContext("beans3.xml"); UserService service = (UserService) context.getBean("userService"); service.list(); service.login("ligson", "admin"); //service.login("ligson", null); } }?
?
4、常用切入点表达式总结