spring学习笔记(14)--AOP Annotation

来源:互联网 发布:手机视频剪辑合成软件 编辑:程序博客网 时间:2024/05/17 23:33

1.LogInterceptor.java

package org.sh.spring.aop;import org.aspectj.lang.annotation.After;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Before;import org.springframework.stereotype.Component;@Aspect@Componentpublic class LogInterceptor {@Before("execution(public * org.sh.spring.impl..*.*(..))")public void before() {System.out.println("method start...");}@After("execution(public * org.sh.spring.impl..*.*(..))")public void after() {System.out.println("method start...");}}


execution(public * org.sh.spring.impl..*.*(..))

表示 org.sh.spring.impl中包括子包中的任何类的任何返回类型的public型方法

2.测试:

@Testpublic void testSave() {ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");IUserDAO ud = (UserServices)ctx.getBean("userservice");User u = new User();ud.save(u);}

测试结果:
method start...
user saved
method done...

3.用@PointCut来实现

LogInterceptor.java

package org.sh.spring.aop;import org.aspectj.lang.annotation.After;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Before;import org.aspectj.lang.annotation.Pointcut;import org.springframework.stereotype.Component;@Aspect@Componentpublic class LogInterceptor {@Pointcut("execution(public * org.sh.spring.impl..*.*(..))")public void myMethod(){}@Before("myMethod()")public void before() {System.out.println("method start...");}@After("myMethod()")public void after() {System.out.println("method start...");}}
相当于用一个方法的名字来命名

@AfterThrowing

@AfterThrowing("myMethod()")public void afterThrowing() {System.out.println("method Throwing...");}
测试结果

method start...
user saved
method done...

method Throwing...

@Around

@Around("myMethod()")public void around(ProceedingJoinPoint pjp) throws Throwable {System.out.println("method around start...");pjp.proceed();System.out.println("method around end...");}

测试结果:

method start...
method around start...
user saved
method done...
method Throwing...

遇到的问题

在将org.sh.spring.impl改为org.sh.spring.services时,程序报错:

java.lang.ClassCastException: $Proxy13 cannot be cast to org.sh.spring.Services.UserServices

原因:

因为我的类是实现了接口的 所以在实例化是一定要用父接口才行将

@Testpublic void testSave() {ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");UserServices = (UserServices)ctx.getBean("userservice");User u = new User();ud.save(u);}

改为:

@Testpublic void testSave() {ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");IUserDAO ud = (IUserDAO)ctx.getBean("userservice");User u = new User();ud.save(u);}

再进行测试就正确了

0 0
原创粉丝点击