Spring AOP 整理
在 xml中加
xmlns:aop="http://www.springframework.org/schema/aop"
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<aop:aspectj-autoproxy />
然后再要添加的方法前添加
@Aspect
@Component
在然后写织入点语法
@Pointcut("execution(public * com.bjsxt.service..*.add(..))")
public void myMethod(){};
@Before("myMethod()")
写添加方法
@Around("myMethod()")
写添加方法
例如:
package com.bjsxt.aop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class LogInterceptor {
@Pointcut("execution(public * com.bjsxt.service..*.add(..))")
public void myMethod(){};
@Before("myMethod()")
public void before() {
System.out.println("method before");
}
@Around("myMethod()")
public void aroundMethod(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("method around start");
pjp.proceed();
System.out.println("method around end");
}
}
还有一种是把aop写在xml文件中
<bean id="logInterceptor" class="com.bjsxt.aop.LogInterceptor"></bean>
<aop:config>
<aop:aspect id="logAspect" ref="logInterceptor">
<aop:before method="before" pointcut="execution(public * com.bjsxt.service..*.add(..))" />
</aop:aspect>
</aop:config>
package com.bjsxt.aop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
//@Aspect
//@Component
public class LogInterceptor {
//@Pointcut("execution(public * com.bjsxt.service..*.add(..))")
public void myMethod(){};
//@Before("myMethod()")
public void before() {
System.out.println("method before");
}
//@Around("myMethod()")
public void aroundMethod(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("method around start");
pjp.proceed();
System.out.println("method around end");
}
}