Aop使用姿势

1.注解方式使用


    org.springframework.boot
    spring-boot-starter-aop


/**
 * @Auther: honghe
 * @Date: 2019/10/28 20:05
 * @Description:aopdemo
 */
@Aspect
@Component
public class MyDemoAop {

    //定义切点democontrol.rest下的所有方法
    @Pointcut("execution(public * com.example.depy.democontrol.rest.*.*(..))")
    public void demoAopPointcut() {
    }

    //方法前执行完后执行
    @Before("demoAopPointcut()")
    public void doBefore(JoinPoint joinPoint) {

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
            .getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();//获取request请求
    }

    //方法执行完后执行
    @After("demoAopPointcut()")
    public void doAfter() {

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
            .getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();//获取request请求
        request.getServletPath();

    }

    //目标方法返回数据后执行
    @AfterReturning(returning = "object", pointcut = "demoAopPointcut()")
    public void doAfterReturn(Object object) {
        System.out.println(object.toString());
    }
}

2.配置方式使用
新增进行aop的java代码

/**
 * @Auther: honghe
 * @Date: 2019/10/28 20:05
 * @Description:aopdemo
 */

public class MyDemoAop2 {

    public void doBefore(JoinPoint joinPoint) {

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
            .getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();//获取request请求
        System.out.println("xml配置生成的aop");
    }

    public void doAfter() {

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
            .getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();//获取request请求
        request.getServletPath();

    }

    public void doAfterReturn(Object object) {
        System.out.println(object.toString());
    }
}

classpath下增加spring-aop.xml配置文件





    

    
    
        
        
            
            
            
            

            
        

    


/*
    classpath下增加spring-aop.xml配置文件 并在启动类进行导入
*/
@SpringBootApplication
@ComponentScan(basePackages = "com.example")
@ImportResource("classpath:spring-aop.xml")
public class RestBeanApplication implements WebMvcConfigurer {
    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(RestBeanApplication.class);
        application.addInitializers(new MyApplicationContextInitializer());
        application.run(args);
    }
}

你可能感兴趣的:(Aop使用姿势)