Spring aop @args 用法 demo(—)

首先说下@args定义:

通过判别目标方法运行时入参对象类是否标注特定注解来指定连接点。如@args(com.yuan.advice.args.PrintArgs) 表示任何一个目标方法,如果方法入参类标注了PrintArgs注解,该方法就会被拦截。

配置文件:
spring-args.xml


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <context:component-scan base-package="com.yuan.advice.args" />
    <aop:aspectj-autoproxy proxy-target-class="true"/>
beans>

注解类:

@Component
@PrintArgs(name = "parmentModel")
public class ParentModel
{
    Logger logger = LoggerFactory.getLogger(ParentModel.class);

    public void methodA(String hello)
    {
        logger.info("parmentModel method");
    }
}

切面类

@Component
@Aspect
@Order(-1)
public class ArgsAspect
{
    Logger logger = LoggerFactory.getLogger(ArgsAspect.class);

    @Before("@args(PrintArgs)")
    public void printArgs(JoinPoint joinPoint)
    {
        logger.info("{},此方法入参数标注了PrintArgs注解",joinPoint.getSignature());
    }
}

入参类

@Component
@PrintArgs(name = "parmentModel")
public class ParentModel
{
    Logger logger = LoggerFactory.getLogger(ParentModel.class);

    public void methodA(String hello)
    {
        logger.info("parmentModel method");
    }
}

目标类:

@Component
public class ArgsModel
{
    Logger logger = LoggerFactory.getLogger(ArgsModel.class);
    public void testArgs(ParentModel parentModel)
    {
       logger.info("入参为{}",parentModel);
    }
}

Test类:

public class ArgsAspectTest
{
    public static void main(String[] args)
    {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-args.xml");

        ArgsModel argsModel = (ArgsModel)context.getBean("argsModel");
        ParentModel parentModel = (ParentModel)context.getBean("parentModel");
        argsModel.testArgs(parentModel);
    }

}

运行结果:
17:44:55.291 [main] INFO com.yuan.advice.args.ArgsAspect - void com.yuan.advice.args.ArgsModel.testArgs(ParentModel),此方法入参数标注了PrintArgs注解
17:44:55.339 [main] INFO com.yuan.advice.args.ArgsModel - 入参为com.yuan.advice.args.ParentModel@31e5415e。

  • 以上为简单spring aop @args用法小demo 。

你可能感兴趣的:(spring)