赞
踩
硬编码的方法会导致耦合度太高,不易修改。
代码使用简单,重点理解这种思想
【单独定义组件】
这个组件不会与我们的已有系统发生关系,不需要额外的去主动调用。
代码体会:
package com.nowcoder.community.aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
/**
* @Projectname: community
* @Classname: AlphaAspect
* @Author: Ding Jiaxiong
* @Date:2023/4/19 18:49
*/
@Component
@Aspect
public class AlphaAspect {
// 定义切点
@Pointcut("execution(* com.nowcoder.community.service.*.*(..))")
public void pointcut() {
}
@Before("pointcut()")
public void before() {
System.out.println("before");
}
@After("pointcut()")
public void after() {
System.out.println("after");
}
@AfterReturning("pointcut()")
public void afterRetuning() {
System.out.println("afterRetuning");
}
@AfterThrowing("pointcut()")
public void afterThrowing() {
System.out.println("afterThrowing");
}
@Around("pointcut()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("around before");
Object obj = joinPoint.proceed();
System.out.println("around after");
return obj;
}
}
这样就对所有的业务都生效了。
直接启动服务器,访问首页
可以看到,到处都是
当然因为我们代码中并没有报错,所以没有那两个throw 的输出。
【实现需求:记日志】
记录啥呢? 用户在xx 时间访问了xxx 方法。
package com.nowcoder.community.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @Projectname: community
* @Classname: ServiceLogAspect
* @Author: Ding Jiaxiong
* @Date:2023/4/19 19:02
*/
@Component
@Aspect
public class ServiceLogAspect {
private static final Logger logger = LoggerFactory.getLogger(ServiceLogAspect.class);
@Pointcut("execution(* com.nowcoder.community.service.*.*(..))")
public void pointcut() {
}
@Before("pointcut()")
public void before(JoinPoint joinPoint) {
// 用户[1.2.3.4],在[xxx],访问了[com.nowcoder.community.service.xxx()].
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String ip = request.getRemoteHost();
String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
String target = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
logger.info(String.format("用户[%s],在[%s],访问了[%s].", ip, now, target));
}
}
直接重启服务器看看,访问首页
没问题,每一个业务都使用到了这个通知【在访问前】。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。