您的位置:首页 > 编程语言 > Java开发

spring boot中使用AOP

2017-07-25 21:17 316 查看
spring boot 中使用AOP,需要先在pom.xml中添加依赖:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>

然后编写切面程序,例如:
@Aspect
@Component
public class HttpAspect {

private static final Logger logger=LoggerFactory.getLogger(HttpAspect.class);

//配置切点
@Pointcut("execution(public * com.springboot.controller.GirlController.*(..))")
public void log(){
}

//joinPoint用于获取域切入点方法有关的信息
@Before("log()")
public void doBefore(JoinPoint joinPoint){
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request=requestAttributes.getRequest();
//url
logger.info("url={}",request.getRequestURL());
//method
logger.info("method={}",request.getMethod());
//ip
logger.info("ip={}",request.getLocalAddr());
//类方法
logger.info("class_method={}",joinPoint.getSignature().getDeclaringType()+"."+joinPoint.getSignature().getName());
//方法参数
logger.info("args={}",joinPoint.getArgs());
}

@After("log()")
public void doAfter(){
logger.info("doAfter={}",2222222);
}

//得到response返回的数据,returning代表切入点方法返回的数据
@AfterReturning(returning = "object",pointcut = "log()")
public void doAfterReturning(Object object){
logger.info("response={}",object.toString());
}
}

需要在类上添加@Aspect注解表明这是一个切面,添加@Component注解是为了能够让spring的bean容器对齐进行管理,然后在对应的方法上添加需要表明什么时候执行切面的对应注解,如果需要获取切入点有关方法的信息,可以传入JoinPoint对象。要得到response响应的数据,参考上面@AfterReturning注解的使用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: