天天看點

Spring使用自定義切面(aop)方法時不生效

這裡我以shiro+springboot的一個例子為例,了解為主即可

1.先了解怎麼做到spring切面程式設計(aop)

1).制作切面類

Spring使用自定義切面(aop)方法時不生效
Spring使用自定義切面(aop)方法時不生效

2).在userServiceimpl加入切面注解

Spring使用自定義切面(aop)方法時不生效

2.确定在那裡使用到被切對象

    1).shiro中使用到userService

Spring使用自定義切面(aop)方法時不生效

    2.)在 controller使用到

Spring使用自定義切面(aop)方法時不生效

注意其中config(springboot的啟動類)對象中加載shiro對象 

Spring使用自定義切面(aop)方法時不生效
Spring使用自定義切面(aop)方法時不生效

執行:

controller通路的時候發現無法觸發切面方法

解決:

這是因為在spring加載shiro(UserRealm類)的時候使用此時切面類還沒加載,但是在UserRealm類中又注入了UserServiceImpl類(注意:此時不是代理類,就是個普通類而已,且該類已經注入到spring容器中,不會再注入第二次了),是以在controller調用的userService方法的時候不是代理類,是以無法做到切面。

解決方法:在UserRealm對象中的UserService加上@Lazy注解,延遲注入到Spring容器,讓切面類加載完後再注入