spring boot入门(五) springboot的切面编程aop。最完整、简单易懂、详细的spring boot教程。

手把手写代码:三小时急速入门springboot—企业级微博项目实战--->csdn学院

本文紧接spring boot入门(四)。
aop是面向切面编程,什么是面向切面编程呢?在方法的执行中,方法的执行一般分为方法执行前和方法执行后,有可以根据传入方法的参数、方法的返回值等进行分类。此处我们讲aop,仅仅讲最为基础的方法执行前切面和方法执行后切面。
1.引入pom依赖,代码如下:


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

2.建立aspect包,在此包下建立LogAspect类,我们的业务为TestController类中的hello方法在执行前打印一句话,hello方法在执行后打印一句话(真实场景有判断用户是否登陆、日志添加等)。LogAspect代码如下:

@Aspect
@Component
public class LogAspect {

    @Before("execution(public * com.yxc.controller.HelloWorldController.hello(..))")
    public void before(){
        System.out.print("------------------hello 方法执行前-------------------");
    }

    @After("execution(public * com.yxc.controller.HelloWorldController.hello(..))")
    public void after(){
        System.out.print("------------------hello 方法执行后-------------------");
    }
}


3.测试,在浏览器访问hello的方法接口,测试结果如下:

我们成功在hello方法执行前和方法执行后切入了before方法和after方法;

注意:@Aspect为aop的关键注解。

你可能感兴趣的:(springboot)