AOP基于注解实现
切面类
@Component //控制反转
@Aspect //声明切面类
public class ForumAdvisor {
//execution(* com.mitu.aspect.*.removeTopic(..))切点
@Before(“execution(* com.mitu.aspect.*.removeTopic(..))”) //声明前置增强
public void before(JoinPoint jPoint) throws Throwable {
System.out.println(“这是前置增强”);
//获取目标对象包全名
String classType=jPoint.getTarget().getClass().getName();
Class<?> clazz=Class.forName(classType);
String className = clazz.getName();
System.out.println(className);
//获取目标对象类名
String classSimpleName = clazz.getSimpleName();
System.out.println(classSimpleName);
//获取目标对象方法名
String methodName = jPoint.getSignature().getName();
System.out.println(methodName);
//获取目标对象参数值
Object\[\] args = jPoint.getArgs();
System.out.println("参数:"+args\[0\]);
\}
@After("execution(\* com.mitu.aspect.\*.\*(..))") //声明后置增强
public void after() \{
System.out.println("这是后置增强");
\}
@Around("execution(\* com.mitu.aspect.\*.\*(..))") //声明环绕增强
public Object around(ProceedingJoinPoint point) throws Throwable\{
//计算方法耗时
System.out.println("这是环绕增强(前置增强)");
long start = System.currentTimeMillis();
Object object = point.proceed();
System.out.println("这是环绕增强(后置增强)");
long end = System.currentTimeMillis();
//获取目标对象包全名
String classType=point.getTarget().getClass().getName();
Class<?> clazz=Class.forName(classType);
String className = clazz.getName();
//获取目标对象方法名
String methodName = point.getSignature().getName();
System.out.println(className+":"+methodName+"耗时"+(end-start));
return object;
\}
@AfterThrowing(pointcut="execution(\* com.mitu.aspect.\*.\*(..))",throwing="ex") //声明抛出异常增强
public void afterThrowing(Exception ex) \{
System.out.println("这是抛出异常增强");
\}
}
aop.xml配置:
<?xml version=”1.0” encoding=”UTF-8”?>
接口类:
public interface IForumService {
public void removeTopic(int topicId);
public void removeForum(int forumId);
}
实现类:
@Component //控制反转
public class ForumServiceImp implements IForumService{
@Override
public void removeTopic(int topicId) \{
try \{
System.out.println("删除论坛帖子:"+topicId);
//Thread.currentThread()获取当前线程
Thread.currentThread().sleep(600);
\} catch (InterruptedException e) \{
// TODO Auto-generated catch block
e.printStackTrace();
\}
// throw new RuntimeException(“抛出运行时异常”);
}
@Override
public void removeForum(int forumId) \{
try \{
System.out.println("删除论坛板块:"+forumId);
Thread.currentThread().sleep(2000);
\} catch (InterruptedException e) \{
e.printStackTrace();
\}
\}
}
测试类:
public class AnnonationAopTest {
public static void main(String[] args) {
ApplicationContext aContext = new ClassPathXmlApplicationContext(“com/mitu/annonationaop/aop.xml”);
//注意强制类型转换的类型为:接口IForumService
IForumService forumService = (IForumService)aContext.getBean(“forumServiceImp”);
forumService.removeForum(200);
forumService.removeTopic(150);
}
}
还没有评论,来说两句吧...