美文网首页
在springboot中开启aop代码_原创记录

在springboot中开启aop代码_原创记录

作者: 爱踢砖家 | 来源:发表于2020-03-09 21:11 被阅读0次

简介

AOP(Aspect Oriented Programming),面向切面编程。对面向对象编程的补充。

作用是在不修改源代码的前提下,给程序添加业务无关的公共功能。例如日志、事务。

原理

AOP实现方式有两种:JDK代理方式和CGLIB动态代理方式 。 默认情况下会采用Jdk的动态代理实现AOP ;目标对象没有实现接口,必须采用CGLIB的动态代理,用的是继承的方式 。

实例:创建ExceptAspect 增强类 :

pom文件导入依赖

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

@Component
@Aspect
@Slf4j
public class ExceptAspect  {
    @AfterThrowing(pointcut = "within(com.gxc.mdg.controller.*)", throwing = "ex")
    public void handleException(JoinPoint join , Exception ex) throws Exception{
         Class declaringType = join.getSignature().getDeclaringType();
         String clazz = declaringType.getCanonicalName();
         String name = join.getSignature().getName();

         log.error( clazz + name + "error {}", ex.getMessage()  );
     }
}

@EnableAspectJAutoProxy 
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
@Component
@Aspect
@Slf4j
public class LogAspect {

    @Autowired
    ObjectMapper objectMapper ;

    @Pointcut("execution(public * com.longfor.gxc.mdg.controller.*Controller.*(..))")
    public void point() {
    }

    @Before(value ="point()")
    public void before(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        // 这段代码会生成到controller 函数之前运行
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
 
        try {
            log.debug(String.format("method:[%s] uri:[%s] params:[%s]", request.getMethod(), request.getRequestURI(),
                    objectMapper.writeValueAsString(args)));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
}

相关文章

网友评论

      本文标题:在springboot中开启aop代码_原创记录

      本文链接:https://www.haomeiwen.com/subject/awdpdhtx.html