【spring配置】——spring aop配置

来源:互联网 发布:不是淘宝网的禁售商品 编辑:程序博客网 时间:2024/05/15 23:35

aop(切面编程)是spring的一个重要特性。使用aop可以帮助我们完成日志打印,方法统计等等功能。且不需要在代码里添加功能代码。

spring配置aop可以分为XML配置方式和Annotation配置方式:

xml配置:

使用xml方式配置aop,首先要定义切面类:

package com.xy.web.aop;import org.aspectj.lang.JoinPoint;import org.aspectj.lang.ProceedingJoinPoint;import org.joda.time.DateTime;import org.slf4j.Logger;import org.slf4j.LoggerFactory;/** * aop xml切面类 * @author javaw * */public class MethodAopXmlAspect {private static final Logger logger = LoggerFactory.getLogger(MethodAopXmlAspect.class);/** * 定义方法执行之前的方法 * @param joinPoint */public void beforeMethod(JoinPoint joinPoint){//获取目标的类名String className = joinPoint.getTarget().getClass().getName();//得到方法签名String methodName = joinPoint.getSignature().getName();logger.info("*******"+className+"("+methodName+") run start*******!");     }public void afterMethod(JoinPoint joinPoint){//获取目标的类名String className = joinPoint.getTarget().getClass().getName();//得到方法签名String methodName = joinPoint.getSignature().getName();logger.info("*******"+className+"("+methodName+") run end*******!");    }public void throwsMethod(JoinPoint joinPoint,Exception e){//获取目标的类名String className = joinPoint.getTarget().getClass().getName();//获取方法签名        String methodName = joinPoint.getSignature().getName();            logger.info("*******"+className+"("+methodName+")run exception,exeptionName="+joinPoint.getClass().getSimpleName()+"*******!"); }/** * 使用ProceedingJoinPoint类继续执行方法 * @param joinPoint * @return * @throws Throwable  */public Object aroundMethod(ProceedingJoinPoint joinPoint) throws Throwable{String metodName = joinPoint.getSignature().getName();  logger.info("<<<<<<<<method("+metodName+")startTime="+new DateTime().toString("yyyy-MM-dd HH:mm:ss")+">>>>>>>>");//调用被拦截的方法Object object = joinPoint.proceed();logger.info("<<<<<<<<method("+metodName+")endTime="+new DateTime().toString("yyyy-MM-dd HH:mm:ss")+">>>>>>>>");return object;}}
配置xml指定切点和切面等:

<?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:aop="http://www.springframework.org/schema/aop"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="    http://www.springframework.org/schema/beans     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd    http://www.springframework.org/schema/aop     http://www.springframework.org/schema/aop/spring-aop-3.0.xsd    http://www.springframework.org/schema/context     http://www.springframework.org/schema/context/spring-context-3.0.xsd"><!-- *********************Spring AOP配置入口****aop:config  开始aop配置 ****aop:aspect配置一个切面(引入实例化切面类) ****aop:pointcut 表达式(配置在哪些方法上) ****aop:advisoraop建议者,配置aop表达式和建议(事务配置)xml配置方式********************* -->  <!--  xml配置方式 1.实例化切面类 2.配置AOP  -->  <bean id="myAopAspect" class="com.xy.web.aop.MethodAopXmlAspect"/>    <aop:config><aop:aspect id="logAop" ref="myAopAspect">配置所有的Advice,使用正则表达式,配置所有类,所有返回值的方法             <aop:pointcut id="myAdvice" expression="execution (* com.xy.service.*.*(..))"/>              <aop:before method="beforeMethod" pointcut-ref="myAdvice"/>              <aop:after-returning method="afterMethod" pointcut-ref="myAdvice"/>              <aop:after-throwing method="throwsMethod" pointcut-ref="myAdvice" throwing="e"/>              <aop:around method="aroundMethod" pointcut-ref="myAdvice"/>  </aop:aspect>    </aop:config></beans>

定义service和serviceImpl:

package com.xy.service;public interface TestAopService {public void testAop();}
package com.xy.service.serviceImpl;import org.springframework.stereotype.Service;import com.xy.service.TestAopService;@Service(value="testAopService")public class TestAopServiceImpl implements TestAopService {public void testAop() {System.out.println("********这只是一个测试方法************");}}
创建Junit测试类:

package base;import org.junit.runner.RunWith;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;/** * Junit测试基类 * 继承AbstractJUnit4SpringContextTests * @author javaw * */@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = "classpath:application-context.xml")public class BaseTestCase extends AbstractJUnit4SpringContextTests{}

package testCase;import org.junit.Before;import org.junit.Test;import org.springframework.beans.factory.annotation.Autowired;import com.xy.service.TestAopService;import base.BaseTestCase;public class AopTestCase extends BaseTestCase{@Autowiredpublic TestAopService testAopService;@Beforepublic void setUp() throws Exception {}@Testpublic void testAopCase(){testAopService.testAop();}}

执行后控制台打印:

2016-01-10 16:36:07,161  INFO MethodAopXmlAspect:27 - *******com.xy.service.serviceImpl.TestAopServiceImpl(testAop) run start*******!
2016-01-10 16:36:07,274  INFO MethodAopXmlAspect:54 - <<<<<<<<method(testAop)startTime=2016-01-10 16:36:07>>>>>>>>
********这只是一个测试方法************
2016-01-10 16:36:07,275  INFO MethodAopXmlAspect:57 - <<<<<<<<method(testAop)endTime=2016-01-10 16:36:07>>>>>>>>
2016-01-10 16:36:07,275  INFO MethodAopXmlAspect:35 - *******com.xy.service.serviceImpl.TestAopServiceImpl(testAop) run end*******!

Annotaion配置:

创建切面类,并添加注解:

package com.xy.web.aop;import org.aspectj.lang.JoinPoint;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.AfterReturning;import org.aspectj.lang.annotation.AfterThrowing;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Before;import org.aspectj.lang.annotation.Pointcut;import org.joda.time.DateTime;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Component;/** * aop annotation切面类 * @author javaw * @aspect 表明是个aop切面类 * @Before @Around括号跟表达式就可以 * @AfterReturning(value="pointcut()")   要加value * @AfterThrowing(value="pointcut()",throwing="e") 要加value 和throwing */@Aspect@Componentpublic class MethodAopAnnotationAspect {private static final Logger logger = LoggerFactory.getLogger(MethodAopAnnotationAspect.class);/** * 切点表达式(可定义多个) */@Pointcut("execution (* com.xy.service.*.*(..))")public void pointcut(){}/** * 定义方法执行之前的方法 * @param joinPoint */@Before("pointcut()")public void beforeMethod(JoinPoint joinPoint){//获取目标的类名String className = joinPoint.getTarget().getClass().getName();//得到方法签名String methodName = joinPoint.getSignature().getName();logger.info("*******"+className+"("+methodName+") run start*******!");     }@AfterReturning(value="pointcut()")public void afterMethod(JoinPoint joinPoint){//获取目标的类名String className = joinPoint.getTarget().getClass().getName();//得到方法签名String methodName = joinPoint.getSignature().getName();logger.info("*******"+className+"("+methodName+") run end*******!");    }@AfterThrowing(value="pointcut()",throwing="e")public void throwsMethod(JoinPoint joinPoint,Exception e){//获取目标的类名String className = joinPoint.getTarget().getClass().getName();//获取方法签名        String methodName = joinPoint.getSignature().getName();            logger.info("*******"+className+"("+methodName+")run exception,exeptionName="+joinPoint.getClass().getSimpleName()+"*******!"); }/** * 使用ProceedingJoinPoint类继续执行方法 * @param joinPoint * @return * @throws Throwable  */@Around("pointcut()")public Object aroundMethod(ProceedingJoinPoint joinPoint) throws Throwable{String metodName = joinPoint.getSignature().getName(); Object object = null;logger.info("<<<<<<<<method("+metodName+")startTime="+new DateTime().toString("yyyy-MM-dd HH:mm:ss")+">>>>>>>>");//调用被拦截的方法object = joinPoint.proceed();logger.info("<<<<<<<<method("+metodName+")endTime="+new DateTime().toString("yyyy-MM-dd HH:mm:ss")+">>>>>>>>");return object;}}
配置xml文件:

<?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:aop="http://www.springframework.org/schema/aop"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="    http://www.springframework.org/schema/beans     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd    http://www.springframework.org/schema/aop     http://www.springframework.org/schema/aop/spring-aop-3.0.xsd    http://www.springframework.org/schema/context     http://www.springframework.org/schema/context/spring-context-3.0.xsd"><!-- *********************Spring AOP配置入口********************* --> <!-- annotation配置方式  --> <!--  aop配置自动扫描 aop annotation类com.xy.web.aop.MethodAopAnnotationAspect -->  <aop:aspectj-autoproxy/></beans>
执行上面的测试类后打印:

2016-01-10 16:51:10,105  INFO MethodAopAnnotationAspect:78 - <<<<<<<<method(testAop)startTime=2016-01-10 16:51:10>>>>>>>>
2016-01-10 16:51:10,106  INFO MethodAopAnnotationAspect:47 - *******com.xy.service.serviceImpl.TestAopServiceImpl(testAop) run start*******!
********这只是一个测试方法************
2016-01-10 16:51:10,106  INFO MethodAopAnnotationAspect:81 - <<<<<<<<method(testAop)endTime=2016-01-10 16:51:10>>>>>>>>
2016-01-10 16:51:10,107  INFO MethodAopAnnotationAspect:56 - *******com.xy.service.serviceImpl.TestAopServiceImpl(testAop) run end*******!



0 0
原创粉丝点击