如果要使用Spring AOP功能,则要在XML里面加入下面命名空间
然后在xsi:schemaLocation里面引入
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
最后在XML配置文件上加入:
然后在xml配置文件里面引入:
xmlns:aop="http://www.springframework.org/schema/aop"
然后在xsi:schemaLocation里面引入
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
最后在XML配置文件上加入:
<aop:aspectj-autoproxy/>
/**
*切面
* @author alcaplz
*定义完要交给spring容器取管理,否则不会生效
*execution (* com.service.impl.PersonServiceBean.*(..))含义是
*拦截com.service.impl.PersonServiceBean这个类下面的所有方法
*AOP表达式语言:@Pointcut("execution (* cn.itcast.service..*.*(..))")
* 含义:
* execution 执行拦截
* * 返回值类型,*代表任何返回类型
* cn.itcast.service 包名
* .. 代表子包底下的所有类
* * 代表拦截所有类
* .* 代表拦截所有方法
* (..) 代表方法参数是任意个
*/
@Aspect
public class MyInterceptor {
@Pointcut("execution (* com.service.impl.PersonServiceBean.*(..))")
public void anyMethod() { //声明一个切点
}
@Before("anyMethod() && args(name)") //如果需要给方法增加参数,则用&& args(方法名)
public void doAccessCheck(String name){ //前置通知
System.out.println("在业务方法执行前执行..");
}
@AfterReturning(pointcut="anyMethod()",returning="result") //如果要获取返回结果
public void doAfterReturning(String result){ //后置通知
System.out.println("在业务方法执行后执行..");
}
@After("anyMethod()")
public void doAfter(){ //最终通知
System.out.println("最终通知 ..");
}
@AfterThrowing(pointcut="anyMethod()",throwing="e") //如果要获取异常
public void doThrowing(Exception e){ //意外通知
System.out.println("出现异常后执行..");
}
@Around("anyMethod()")
public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable{
System.out.println("环绕通知..");
//环绕通知,开发的时候做权限拦截经常被用到
//其实如果实现了环绕通知这个方法,则可以在此方法内部进行上面的各种通知,而不用在上面写多个方法
//如果使用了环绕通知,则必须保证在环绕通知内部执行此方法,这方法类似struts2的invoke()
//if(){ 判断用户是否有权限
Object obj = pjp.proceed();
//}
return obj;
}
}
然后在xml配置文件里面引入:
<bean id="myInterceptor" class="com.service.impl.MyInterceptor"></bean>
<bean id="personService" class="com.service.impl.PersonServiceBean"></bean>