springAOP--学习和理解--用STS4搭建一个AOP演示示例02

版权声明:本文为博主原创文章,经博主允许,可自由共享,尽量不要用于商业用途。 https://blog.csdn.net/matrixbbs/article/details/90669727

AOP是Spring的重要功能之一

  • 很多时候,AOP直接可以用于:数据库事务,业务日志,安全检查,权限控制等功能中
  • 而SpringBoot项目里,可以使用AspectJ的注解来实现AOP功能

项目创建

File>New>Spring Starter Project
创建项目时,选中web,devtools
创建完成后,项目结构如下
在这里插入图片描述
工作点在红框中

1 首先添加依赖,主要是AOP依赖

在pom.xml文件中添加依赖,保存并刷新

		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.6.11</version>
		</dependency>

最新的版本到了1.9.12,但建议用老一点的稳定版本。如果相应的注解用不了,多半是依赖的包没有下载完。具体本人也没有查到原因,下载多次,仍然不对,但用老一点的版本,比如这里的1.6.11,一次就对了。

2 新建业务类和代理类

这里,模拟的仅仅只是在控制台输出的方式,模拟一个销售业务类
类名:SaleServiceImpl.java

package com.fhzheng.demo.aop;

import org.springframework.stereotype.Component;

@Component
public class SaleServiceImpl {

	public void saleService() {

		System.out.println(">>>>>销售业务。。。");
	}

}

代理类也仅仅只是用屏显的方式,完成AOP切面的切入,演示的是之前和之后的切面执行
类名是:ProxyService.java

package com.fhzheng.demo.aop;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class ProxyService {

	@Before("execution(* com.fhzheng.demo.aop.*ServiceImpl.*(..))")
	public void before() {
		System.out.println("业务方法调用前执行切面");
	}
	
	@After("execution(* com.fhzheng.demo.aop.*ServiceImpl.*(..))")
	public void after() {
		System.out.println("业务方法调用后执行切面");
	}
}

要特别注意,切点表达式的写法,这里的写法,其实就是对业务类里所有的方法均加载相应的前后切面动作【即前置通知和后置通知】

3 启动器与控制器实现,这里用的是同一个类来实现的

SpringAoPdemo03Application.java,得益于SpringBoot工具和STS4工具提供的方便,创建出来的项目,默认就是这个文件。
需要做的内容是

  • 0 本质上,它只是一个启动器
  • 1 添加相应的注解,让启动器同时也作为控制器来用,加上@RestController注解
  • 2 注入一个业务类,即@Autowired一个SaleServiceImpl对象
  • 3 添加一个控制器访问URL,即加一个@GetMapping()注解
package com.fhzheng.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fhzheng.demo.aop.SaleServiceImpl;

@SpringBootApplication
@RestController
public class SpringAoPdemo03Application {

	public static void main(String[] args) {
		SpringApplication.run(SpringAoPdemo03Application.class, args);
	}
	
	@Autowired
	SaleServiceImpl saleService;
	
	@GetMapping("/sale")
	public String saleService() {
		saleService.saleService();
		System.out.println("SaleServiceImpl的class:"+saleService.getClass());
		return "";
	}

}

4 启动,然后打开浏览器访问相应的地址

5 代理类的分析

  • 从结果可以看出,组织切面比之前要方便了很多
  • 输出的代理类是经过CGLIB处理的类,即用的是类代理方式,而不是用的JDK本身的接口代理方式
  • 事实上,在SpringBoot 2.0 中,默认情况下,不管是接口还是类代理,都使用CGLIB代理
    • 如果要使用JDK的动态代理,则应设置相应的参数,即spring.aop.proxy-target-class,值设为false即可
    • SpringBoot里,使用的是Spring AOP,功能强大,值得进一步去探索

猜你喜欢

转载自blog.csdn.net/matrixbbs/article/details/90669727