今天折腾AOP,加入了spring3.2.4的包以后,一直报错
还需要添加
aspectjrt.jar
aspectjweaver.jar
aopalliance-1.0.jar
这种实现方式必须加
UserManagerImpl的接口,如果不想加接口,需要cglib包。
(1)先看配置
<
bean
id
=
"securityManager"
class
=
"com.gxw.spring.manager.SecurityManager"
></
bean
>
<
bean
id
=
"userManager"
class
=
"com.gxw.spring.manager.UserManagerImpl"
></
bean
>
<
aop:config
>
<
aop:aspect
id
=
"security"
ref
=
"securityManager"
>
<
aop:pointcut
id
=
"addMethod"
expression
=
"execution(* com.gxw.spring.manager.UserManagerImpl.add*(..))"
/>
<
aop:before
method
=
"txAdvice"
pointcut-ref
=
"addMethod"
/>
</
aop:aspect
>
</
aop:config
>
(2)通过配置可以看到有切面
aspect ,切点
pointcut,还有advice
aop:before,AOP是面向切面的编程,spring AOP是通过对方法进行横切来实现 面向切面编程的。
可以先想象在
UserManagerImpl类add()方法上面横切一刀,
切面
aspect ->
ref
=
"securityManager"。
面上有很多很多点,其中每一个点对应一种方法,我们可以配置哪些方法会命中。所以切点
pointcut ->
expression
=
"execution(* com.gxw.spring.manager.UserManagerImpl.add*(..))"。
最后,需要在
切点上的配置
策略 advice,切面类的的方法
method
=
"txAdvice" ->
pointcut-ref
=
"addMethod"。
可能这样完了,我们还不是特别明白,那么现在我需要再添加一个切面log。直接上配置,一目了然。
<
bean
id
=
"securityManager"
class
=
"com.gxw.spring.manager.SecurityManager"
></
bean
>
<
bean
id
=
"userManager"
class
=
"com.gxw.spring.manager.UserManagerImpl"
></
bean
>
<
bean
id
=
"logManager"
class
=
"com.gxw.spring.manager.LogManagerImpl"
></
bean
>
<
aop:config
>
<
aop:aspect
id
=
"security"
ref
=
"securityManager"
>
<
aop:pointcut
id
=
"addMethod"
expression
=
"execution(* com.gxw.spring.manager.UserManagerImpl.add*(..))"
/>
<
aop:before
method
=
"txAdvice"
pointcut-ref
=
"addMethod"
/>
</
aop:aspect
>
<
aop:aspect
id
=
"log"
ref
=
"logManager"
>
<
aop:pointcut
expression
=
"execution(* com.gxw.spring.manager.UserManagerImpl.add*(..))"
id
=
"addMethod"
/>
<
aop:after
method
=
"loggger"
pointcut-ref
=
"addMethod"
/>
</
aop:aspect
>
</
aop:config
>