Posted on 2008-05-08 10:08
G_G 阅读(4319)
评论(1) 编辑 收藏 所属分类:
Spring 、
AOP
我的aop 基础
spring 实际使用 (这就使用一个例子说明)
测试类以及结果:
package unit;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import bean.HelloService;
public class Main {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
"beans.xml");
HelloService service = (HelloService) context.getBean("helloService");
service.annotationAop();
System.out.println();
service.xmlAop();
}
}
结果:
annotationAop//正常方法运行
aop--AspectJ! //annotation拦截
xmlAop //正常方法运行
aop--XmlAop! //配置拦截
use jar- --aspectjrt.jar
- --aspectjweaver.jar
- --acglib-nodep-2.1_3.jar
- --commons-logging.jar
- --spring.jar
- --spring-aspects.jar
XML配置<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"
xsi:schemaLocation=
"http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 测试使用类 分别由 方法 annotationAop/xmlAop -->
<bean id="helloService"
class="bean.HelloService"/>
<!-- annotation aop 拦截 使用@Aspect
@Pointcut("execution(* annotationAop(..))")
@AfterReturning("mainMethod()")
-->
<bean id="xmlAop"
class="aop.AnnotationAspectJ"/>
<aop:aspectj-autoproxy/>
<!-- xml aop 配置文件拦截 -->
<bean id="XmlAspectJ"
class="aop.XmlAspectJ"/>
<aop:config>
<aop:aspect ref="XmlAspectJ">
<aop:pointcut id="mainMethod" expression="execution(* xmlAop(..))"/>
<aop:after-returning pointcut-ref="mainMethod" method="goXmlAop"/>
</aop:aspect>
</aop:config>
</beans>
HelloService.java
package bean;
public class HelloService {
public void annotationAop() {
System.out.println(" annotationAop ");
}
public void xmlAop(){
System.out.println(" xmlAop ");
}
}
AnnotationAspectJ.java
package aop;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
@Aspect
public class AnnotationAspectJ {
@Pointcut("execution(* annotationAop(..))")
public void mainMethod() {}
@AfterReturning("mainMethod()")
public void sayHello() {
System.out.println("aop--AspectJ!");
}
}
XmlAspectJ.java
package aop;
public class XmlAspectJ {
public void goXmlAop(){
System.out.println(" aop--XmlAop! ");
}
}