天天看点

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容器,让切面类加载完后再注入