1、导包
2、编写切面类,在切面类上直接使用AOP注解
package
star.july.e_spring_aop_annotation;
import
org.aspectj.lang.ProceedingJoinPoint;
import
org.aspectj.lang.annotation.After;
import
org.aspectj.lang.annotation.Around;
import
org.aspectj.lang.annotation.Aspect;
import
org.aspectj.lang.annotation.Before;
//使用注解AOP
@Aspect
//代表一个切面类
public
class
MyAspect {
/**
* 常用的通知类:
* 前置通知: 在目标对象的连接点之前调用
* 后置通知:在目标对象的连接点之后调用
* 环绕通知: 在目标对象的连接点之前与之后调用
*/
@Before
(value =
"execution(* star.july.*.UserDao.*())"
)
public
void
before(){
System.
out
.println(
"开启事务"
);
}
//定义后置通知
@After
(value =
"execution(* star.july.*.UserDao.update())"
)
public
void
after(){
System.
out
.println(
"结束事务"
);
}
//环绕通知
@Around
(value =
"execution(* star.july.*.UserDao.*())"
)
public
void
round(ProceedingJoinPoint jp)
throws
Throwable{
System.
out
.println(
"环绕通知前面代码"
);
//执行目标对象的核心方法
jp.proceed();
//执行连接点方法
System.
out
.println(
"环绕通知后面代码"
);
}
}
3、编写dao类
package
star.july.e_spring_aop_annotation;
public
class
UserDao{
//调用业务方法
public
void
save(){
System.
out
.println(
"调用save方法"
);
}
public
void
update(){
System.
out
.println(
"调用update方法"
);
}
}
4、配置
<?
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: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"
>
<!-- 1.创建目标对象 -->
<
bean
id
=
"userDao"
class
=
"star.july.e_spring_aop_annotation.UserDao"
></
bean
>
<!-- 2.创建切面类对象 -->
<
bean
id
=
"myaspect"
class
=
"star.july.e_spring_aop_annotation.MyAspect"
></
bean
>
<!-- 注意:注解方式必须开启自动创建代理类配置 -->
<
aop:aspectj-autoproxy
></
aop:aspectj-autoproxy
>
</
beans
>
5、测试
package star.july.e_spring_aop_annotation;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Demo {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("/applicationContext.xml");
UserDao userDao = (UserDao)ac.getBean("userDao");
userDao.save();
userDao.update();
}
}
可以参考上一篇文章,下方有链接