admin管理员组文章数量:1794759
Spring MVC和Spring配置AOP
1.首先Spring MVC和Spring是两个东西,配置文件是分开的,配置文件的加载也是分开的。所以要想给Spring MVC的Controller添加AOP的话,得在Spring MVC的配置文件中配置,要想给Service和Repository添加AOP的话得在Spring的配置文件中配置。 2.以一个例子说明,有人配置了Service层的事务AOP之后,事务不起作用。原因是在Spring MVC中配置的扫描规则,将Service也扫描了,这是Spring的配置文件还没有加载,也就还没有对Service层的类添加事务AOP,当加载Spring的配置文件时,再次扫描Service层,发现Service层的类都已经再容器里了,就不往容器里放了,也就是此时加到Spring容器里的Service都是没有添加事务AOP之前的类。解决这个问题的思路很简单,就是在Spring MVC的配置文件中配置,只扫描Controller层的类,不扫描Service层的类,Service层的类在Spring的配置文件中扫描。 3.要实现上述效果,首先看如下的代码
<aop:aspectj-autoproxy proxy-target-class="true"/> <!-- 扫描@Controller组件 --> <!-- 提示:将com.corp.app该为您的业务系统的包路径 --> <context:component-scan base-package="cn.osworks.aos;cn.usmaker.system.plugin;com.mycorp.mysystem" use-default-filters="false"> <context:include-filter type="annotation" expression="org.aspectj.lang.annotation.Aspect" /> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /> <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice" /> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/> </context:component-scan>use-default-filters="false"的作用是禁用默认的扫描规则,使用自己配置的扫描规则。也就是在context:component-scan 标签内,context:include-filter 标签里配置的规则,会被扫描,context:exclude-filter 配置的规则不会被扫描。 上边的配置是Spring MVC的配置文件中的配置,只扫描带有org.aspectj.lang.annotation.Aspect和org.springframework.stereotype.Controller、org.springframework.web.bind.annotation.ControllerAdvice的标记。 Spring的配置如下:
<aop:aspectj-autoproxy/> <!-- Spring服务组件扫描(排除@Controller相关组件) --> <!-- 请将com.mycorp.mysystem.**改为你的项目扫描路径 --> <context:component-scan base-package="cn.osworks.aos;cn.usmaker.system.plugin;com.mycorp.mysystem" use-default-filters="false"> <context:include-filter type="annotation" expression="org.aspectj.lang.annotation.Aspect" /> <context:include-filter type="annotation" expression="org.springframework.stereotype.Service" /> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> <context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice" /> </context:component-scan>只扫描org.aspectj.lang.annotation.Aspect和org.springframework.stereotype.Service标记的类。 4.注意Spring MVC中的配置和Spring的配置的一点区别 在Spring MVC的配置是
<aop:aspectj-autoproxy proxy-target-class="true"/>在Spring中的配置是
<aop:aspectj-autoproxy/>5.配置的切点尽量精准,这点很重要,要代理哪些类就精确的配置到哪些类,不然很容易代理一些Spring和Spring MVC内部使用的类,容易产生错误,甚至启动不起来。
版权声明:本文标题:Spring MVC和Spring配置AOP 内容由林淑君副主任自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.xiehuijuan.com/baike/1686618820a86945.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论