使用注解进行实现:减少xml文件的配置。
1 建立切面类
不需要实现任何特定接口,按照需要自己定义通知。
package org.guangsoft.utils;
import java.util.Date;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
/***
* 定义用户的切面类
* ***/
@Component
@Aspect
public class UsersAdvice
{
// 前置的通知
@Before("execution(* com.bjsxt.service.impl.*.*(..))")
public void before()
{
System.out.println("before-------------" + new Date());
}
// 后置通知
// @After("execution(* com.bjsxt.service.impl.*.*(..))")
@AfterReturning(pointcut = "execution(* com.bjsxt.service.impl.*.*(..))", returning = "rv")
public void after(Object rv)
{
System.out.println("after-------------" + new Date() + "--------------"
+ rv);
}
/****
* 环绕通知
* **/
@Around("execution(* com.bjsxt.service.impl.*.*(..))")
public void around(ProceedingJoinPoint jp)
{
System.out.println("aroun.---------before-------------" + new Date());
try
{
jp.proceed();// 调用目标方法
}
catch (Throwable e)
{
e.printStackTrace();
} // 调用目标方法
System.out.println("around---------after--------------" + new Date());
}
/***
* 异常通知
* **/
@AfterThrowing(pointcut = "execution(* com.bjsxt.service.impl.*.*(..))", throwing = "ex")
public void exception(Throwable ex)
{
System.out.println("exception-------------------" + ex.getMessage());
}
}
2xml文件配置
<?xml version="1.0" encoding="UTF-8"?>
<!-- 到入xml文件的约束 -->
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd
">
<!-- 开启扫描注解 -->
<context:component-scan
base-package="org.guangsoft.service.impl,org.guangsoft.utils">
</context:component-scan>
<!-- 开启切面的自动代理 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
在开发中是方式二。减少xml配置,实现灵活