Spring在实际运用中可通过注解或者XML配置来实现AOP功能,这里在上一篇的基础上通过Demo来模拟XML配置实现AOP的过程。
代码结构如下
1、Spring配置如下,在<aop:config>中配置好对应的切点pointCut, 然后在切面aspect中引用对应的切点即可。
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <bean id = "dao" class="com.dao.UserDaoImpl"/> <bean id="userService" class="com.service.UserService"> <property name="dao" ref="dao"></property> </bean> <bean id = "logInter" class="com.handler.LogInterceptor"/> <aop:config> <aop:pointcut expression="execution(* com.service.UserService.*(..))" id="servicePointCut" /> <aop:aspect id="LogAop" ref="logInter"> <aop:before method="beforeExcute" pointcut-ref="servicePointCut"/> </aop:aspect> </aop:config> </beans>
2、拦截类LogInterceptor
package com.handler; public class LogInterceptor { public void beforeExcute(){ System.out.println("aspect execute."); } }
3、在UserService中通过Spring注入Dao层,完成接口调用。
测试类如下:
package com.test; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.service.UserService; public class TestAopAnnotation { @Test public void testAopAnnotation(){ ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); UserService service = (UserService) context.getBean("userService"); service.save(); } }
测试结果: