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内部使用的类,容易产生错误,甚至启动不起来。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陈振阳

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值