复习一下Spring AOP利用注解的形式,配置一个简单的@Before事前通知
首先定义一个切面,注意添加@Aspect之后,Spring不会对该类进行增强处理,定义@Before事前通知,使用@Before来标注一个方法时,该方法就被定义成事前通知,通常需要指定@Before一个属性值value,该属性值指定一个切入点表达式,在匹配这个表达式的方法执行之前,被定义成事前通知的authority()方法将会先执行。
package org.crazyit.app.advice;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
//定义一个切面
@Aspect
public class BeforeAdviceTest {
//匹配org.sun.service.impl包下的所有类的、所有方法的执行作为切入点
@Before("execution(* org.crazyit.app.service.impl.*.*(..))")
public void authority(){
System.out.println("模拟权限检查");
}
}
定义一个接口,和该接口的实现类
package org.crazyit.app.service;
public interface Person {
public String sayHello(String name);
public void eat(String food);
}
package org.crazyit.app.service.impl;
import org.crazyit.app.service.Person;
import org.springframework.stereotype.Component;
@Component()
public class Chinese implements Person {
@Override
public String sayHello(String name) {
return name + "Hello,Spring AOP";
}
@Override
public void eat(String food){
System.out.println("我正在吃:"+food);
}
}
applicationContext.xml的配置
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- 启用aspectj支持 -->
<aop:aspectj-autoproxy/>
<context:component-scan base-package="org.crazyit.app.service,org.crazyit.app.advice">
<context:include-filter type="annotation" expression="org.aspectj.lang.annotation.Aspect"/>
</context:component-scan>
<!--<bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator"/>
-->
</beans>
最后查看执行结果: