本帖最后由 大蓝鲸小蟀锅 于 2020-4-10 16:36 编辑  
 
SpringBoot使用AOP  
 
  
我们之前在spring的框架中使用aop大家都很熟悉了,但是目前我们使用springboot之后,没有了相关的配置文件,我们如何在springboot中去使用aop呢?下面我们来通过一个demo看一下具体的操作: 
 
 
1. 创建一个新的maven工程,打包方式为war包 
 
 
2. 打开pom.xml文件,导入相关的依赖 
[XML] 纯文本查看 复制代码 <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 [url=http://maven.apache.org/xsd/maven-4.0.0.xsd]http://maven.apache.org/xsd/maven-4.0.0.xsd[/url]">
    <modelVersion>4.0.0</modelVersion>
    <groupId>cn.itcast</groupId>
    <artifactId>TestAop</artifactId>
    <version>1.0-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.6.RELEASE</version>
    </parent>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
    </dependencies>
</project>
 
3.  编写springboot 启动类 
[Java] 纯文本查看 复制代码 
package cn.itcast;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class);
    }
}
 
4. 编写一个controller,准备加入aop
 [Java] 纯文本查看 复制代码 
package cn.itcast.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
    @RequestMapping("/hello")
    public void hello(){
        System.out.printf("正常执行controller");
    }
}
 
5.编写切面类
 [Java] 纯文本查看 复制代码 
package cn.itcast.aop;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
/**
 * 切面类,
 * Component 是把当前类交由spring管理
 * Aspect 声明切面类   (包含 切点和通知)
 */
@Component
@Aspect
public class Aspect1 {
    /**
     * Before这是声明 前置通知
     * 括号内的是切点表达式: 意思是cn.itcast.controller包下所有类所有方法
     */
    @Before("execution(public * cn.itcast.controller..*(..)))")
    public void beforeFunc() {
        System.out.println("前置通知执行了!");
    }
}
 
 
注意:这里和spring 用aop 没有区别 
6. 运行项目 
7. 打开浏览器 访问: http://localhost:8080/hello 
见到浏览器输出内容如下,则完成测试: 
[Shell] 纯文本查看 复制代码 
前置通知执行了!
正常执行controller
  
  |