先说一下相应的知识作铺垫
Spring
的
AOP
术语:
1
)连接点(
JointPoint
):目标对象的每个方法
2
)切入点
(PontCut)
:切入了服务代码的连接点
3
)通知
(Advice)
:在切入点上面需要切入的服务代码
4
)切面
(Aspect/Advisor)
:在指定的切入点切入指定的通知形成切面
1、导入所需的jar包
Spring的IOC和AOP包
2、创建dao类
package
star.july.d_spring_aop;
import
org.aspectj.lang.ProceedingJoinPoint;
public
class
MyAspect {
/**
* 常用的通知类:
* 前置通知: 在目标对象的连接点之前调用
* 后置通知:在目标对象的连接点之后调用
* 环绕通知: 在目标对象的连接点之前与之后调用
*/
//定义前置通知
public
void
before(){
System.
out
.println(
"开启事务"
);
}
//定义后置通知
public
void
after(){
System.
out
.println(
"结束事务"
);
}
//环绕通知
public
void
round(ProceedingJoinPoint jp)
throws
Throwable{
System.
out
.println(
"环绕通知前面代码"
);
//执行目标对象的核心方法
jp.proceed();
//执行连接点方法
System.
out
.println(
"环绕通知后面代码"
);
}
}
3、创建切面类
package
star.july.d_spring_aop;
public
class
MyAspect {
/**
* 常用的通知类:
* 前置通知: 在目标对象的连接点之前调用
* 后置通知:在目标对象的连接点之后调用
* 环绕通知: 在目标对象的连接点之前与之后调用
*/
//定义前置通知
public
void
before(){
System.
out
.println(
"开启事务"
);
}
}
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"
>
<
bean
id
=
"userDao"
class
=
"star.july.d_spring_aop.UserDao"
>
bean
>
<
bean
id
=
"myaspect"
class
=
"star.july.d_spring_aop.MyAspect"
>
bean
>
<
aop:config
>
<
aop:aspect
ref
=
"myaspect"
>
<
aop:pointcut
expression
=
"execution(* star.july.d_spring_aop.UserDao.*(..))"
id
=
"myspt"
/>
<
aop:before
method
=
"before"
pointcut-ref
=
"myspt"
/>
<
aop:after
method
=
"after"
pointcut-ref
=
"myspt"
/>
<
aop:around
method
=
"round"
pointcut-ref
=
"myspt"
/>
aop:aspect
>
aop:config
>
beans
>
5、测试
package
star
.
july
.
d_spring_aop
;
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
();
}
}