问题1:AOP的作用是什么?
问题2:连接点和切入点有什么区别,二者谁的范围大?
问题3:请描述什么是切面?
问题1:在通知方法中如何定义切入点表达式?
问题2:如何配置切面?
问题3:在配置类上如何开启AOP注解功能?
初始环境搭建:
创建目录和类:
导入下面第一步的坐标
pom.xml
4.0.0 cn.whu spring_18_aop_quickstart war 1.0-SNAPSHOT org.springframework spring-context 5.2.10.RELEASE org.aspectj aspectjweaver 1.9.4
基础代码:
@Configuration
@ComponentScan("cn.whu")
public class SpringConfig {
}public interface BookDao {public void save();public void update();
}@Repository
public class BookDaoImpl implements BookDao {public void save() {System.out.println(LocalDateTime.now());System.out.println("book dao save");}public void update() {System.out.println("book dao update ...");}
}//!!!导入一个包 三个注解 Spring就用起来了 !!!
public class App {public static void main(String[] args) {ApplicationContext ioc = new AnnotationConfigApplicationContext(SpringConfig.class);BookDao bookDao = ioc.getBean(BookDao.class);bookDao.save();System.out.println("--------------");bookDao.update();}
}
下面再从AOP角度梳理步骤:前两步环境里已经有了 不需要再做了
org.springframework spring-context 5.2.10.RELEASE org.aspectj aspectjweaver 1.9.4
public interface BookDao {public void save();public void update();
}@Repository
public class BookDaoImpl implements BookDao {public void save() {System.out.println(LocalDateTime.now());System.out.println("book dao save ...");}public void update(){System.out.println("book dao update ...");}
}@Configuration
@ComponentScan("cn.whu")
public class SpringConfig {
}
//通知类必须配置成Spring管理的bean
@Component //肯定给SpringIoC管理呀
public class MyAdvice {public void method(){System.out.println(System.currentTimeMillis());}
}
切入点定义依托一个不具有实际意义的方法进行,即无参数,无返回值,方法体无实际逻辑
@Component //给SpringIoC当做Bean管理 [专业术语: 通知类必须配置成Spring管理的bean]
@Aspect //告诉Spring这是做AOP的 [专业术语: 设置当前类为通知类]
public class MyAdvice {//设置切入点: 也就是定义在谁那里执行//@Pointcut注解要求配置在方法上方@Pointcut("execution(void cn.whu.dao.BookDao.update())")//切入点定义在哪执行private void pt(){}//设置在切入点pt()的前面运行当前操作(前置通知)@Before("pt()")//共性功能(通知)和在哪执行(切入点)绑定起来//定义共性功能public void method(){//方法名任意System.out.println(LocalDateTime.now());}
}
@Configuration
@ComponentScan("cn.whu")
//开启注解开发AOP功能 (因为不确定是xml还是注解方式 所以要注明下)
@EnableAspectJAutoProxy
public class SpringConfig {
}
public class App {public static void main(String[] args) {ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);BookDao bookDao = ctx.getBean(BookDao.class);bookDao.update();}
}
update方法里没有打印时间的代码,是通知方法中的打印时间放执行了,说明对原始方法进行了增强,AOP编程成功
(也就多写了一个类和5个注解)
什么是目标对象?什么是代理对象?
目标对象(Target):被代理的对象,也叫原始对象,该对象中的方法没有任何功能增强。
代理对象(Proxy):代理后生成的对象,由Spring帮我们创建代理对象。
public class App {public static void main(String[] args) {ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);BookDao bookDao = ctx.getBean(BookDao.class);bookDao.update();//打印对象的类名System.out.println(bookDao.getClass());}
}
参考:https://blog.csdn.net/m0_52012606/article/details/122585571
静态代理,实现该类的顶层接口,导入该类对象为属性,重新实现对应的接口方法,在调用方法执行执行前后添加一些操作,就实现了对方法的增强,但是这增强一个方法就得写一个类实现"重写"一次,太麻烦了吧。
景泰代理:传入类全路径.方法,通过反射增强,就简单方便多了
在切入点表达式中如何简化包名和参数类型书写?
切入点:要进行增强的方法
切入点表达式:要进行增强的方法的描述方式
execution(void com.itheima.dao.BookDao.update())
execution(void com.itheima.dao.impl.BookDaoImpl.update())
也就是说切入点描述的是实现类或者接口都ok
切入点表达式标准格式:动作关键字(访问修饰符 返回值 包名.类/接口名.方法名(参数) 异常名)
execution(public User com.itheima.service.UserService.findById(int))
一个一个写也累 所以肯定有通配符匹配的写法
目的:可以使用通配符描述切入点,快速描述。
匹配com.itheima包下的任意包中的UserService类或接口中所有find开头的带有(任意类型)一个参数的方法
execution(public * com.itheima.*.UserService.find*(*))
匹配com包下的任意包中的UserService类或接口中所有名称为findById的方法
execution(public User com..UserService.findById(..))
execution(* *..*Service+.*(..))
*
表示1个
..
表示任意
…
从后往前看,()内肯定是参数,倒数第一个肯定是方法名,倒数第二个肯定类或接口名,再往回倒就不确定了
execution(* *..*.*(..))
任意包下任意方法 可太疯狂了 可不能这么配
execution(* *..u*(..))
任意u开头的方法
execution(* *..*e(..))
任意e结尾的方法
execution(* *…Service+.(…)) 所有Service类或者接口的子类
execution(* cn.whu.*.*Service.find*(..))
所有业务层查询方法加AOP
请描述一下如何定义环绕通知方法?
环境准备,复制一份上面的module,修改如下:
public interface BookDao {public void update();public int select();
}
@Repository
public class BookDaoImpl implements BookDao {@Overridepublic void update() {System.out.println("book dao update is running ...");}@Overridepublic int select() {System.out.println("book dao select is running ...");return 100;}
}@Configuration
@ComponentScan("cn.whu")
@EnableAspectJAutoProxy
public class SpringConfig {}public class App {public static void main(String[] args) {ApplicationContext ioc = new AnnotationConfigApplicationContext(SpringConfig.class);BookDao bookDao = ioc.getBean(BookDao.class);bookDao.update();}
}
@Component
@Aspect
public class MyAdvice {@Pointcut("execution(void cn.whu.dao.BookDao.update())")private void pt(){}public void before(){System.out.println("before advice ...");}public void after(){System.out.println("after advice ...");}public void around(){System.out.println("around before advice ...");System.out.println("around after advice ...");}public void afterReturning(){System.out.println("afterReturning advice ...");}public void afterThrowing(){System.out.println("afterThrowing advice ...");}
}
@Before("pt()")
public void before() {System.out.println("before advice ...");
}
调用上面的测试方法执行update方法,会在方法体执行前执行before()进行打印
@After("pt()")
public void after() {System.out.println("after advice ...");
}
调用上面的测试方法执行update方法,会在方法体执行后执行after()进行打印
@AfterReturning("pt()")
public void afterReturning() {System.out.println("afterReturning advice ...");
}
@AfterThrowing("pt()")
public void afterThrowing() {System.out.println("afterThrowing advice ...");
}
@Around("pt()")
public Object around(ProceedingJoinPoint pjp) throws Throwable {System.out.println("around before advice ...");Object ret = pjp.proceed();//环绕通知有返回值 必须接收下来并原路返回System.out.println("around after advice ...");return ret;
}
调用上面的测试方法执行update方法,会在方法体执行前执行
"around before advice ..."
打印,执行后执行System.out.println("around after advice ...");
打印
环绕通知注意事项
最终aop.MyAdvice.java
@Component
@Aspect
public class MyAdvice {@Pointcut("execution(void cn.whu.dao.BookDao.update())")private void pt(){}@Pointcut("execution(int cn.whu.dao.BookDao.select())")private void pt2(){}//@Before("pt()")public void before(){System.out.println("before advice ...");}//After("pt2()")public void after(){System.out.println("after advice ...");}//@Around("pt()") //最重要最常用public void around(ProceedingJoinPoint pjp) throws Throwable {System.out.println("around before advice ...");//环绕肯定要手动对原始操作进行调用,格式也是固定的pjp.proceed();System.out.println("around after advice ...");}//@Around("pt2()")//原来函数有返回值 环绕通知这里得返回Object类型,接收调用得返回值并返回public Object aroundSelect(ProceedingJoinPoint pjp) throws Throwable {System.out.println("around before advice ...");//环绕肯定要手动对原始操作进行调用,格式也是固定的Object ret = pjp.proceed();System.out.println("around after advice ...");return ret;}//@AfterReturning("pt2()")public void afterReturning(){System.out.println("afterReturning advice ...");}@AfterThrowing("pt2()")public void afterThrowing(){System.out.println("afterThrowing advice ...");}
}
能不能描述一下环绕通知里面的实现步骤?
需求:任意业务层接口执行均可显示其执行效率(执行时长)
分析:
①:业务功能:业务层接口执行前后分别记录时间,求差值得到执行效率
②:通知类型选择前后均可以增强的类型——环绕通知
Spring整合mybatis对spring_db数据库中的Account进行CRUD操作
Spring整合Junit测试CRUD是否OK。
在pom.xml中添加aspectjweaver切入点表达式依赖
… …
环境准备:就是前面spring整合junit(mybatis也整合了)的module(spring_16_spring_junit)复制一份,就是本案例的初始环境
注意加入aspectj依赖
org.aspectj aspectjweaver 1.9.4
@Component
@Aspect
public class ProjectAdvice {@Pointcut("execution(* cn.whu.service.*Service.*(..))")//service层的所有方法 (最后的.*方法名匹配别忘了)private void servicePt(){}//切入点方法 private权限//@Around("servicePt()") //环绕通知 别写错了@Around("ProjectAdvice.servicePt()") //这么写也行 "类名.方法名" 这么写可以引入别的类里面定义的切入点public Object runSpeed(ProceedingJoinPoint pjp) throws Throwable {Signature signature = pjp.getSignature(); //获取执行的签名对象//cn.whu.service.AccountServiceString className = signature.getDeclaringTypeName().toString(); //获取接口/类全限定名//findByIdString methodName = signature.getName(); //获取方法名//cn.whu.service.AccountService.findByIdString classMethodName = className+"."+methodName; //完整名称//System.out.println(classMethodName);//执行万次 并统计时间long start = System.currentTimeMillis();Object ret=null;for(int i=0;i<10000;i++){ret = pjp.proceed();}long end = System.currentTimeMillis();System.out.println(classMethodName +" 的万次运行时间: "+(end-start)+" ms");return ret;}
}
@Configuration
@ComponentScan("com.itheima")
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class,MybatisConfig.class})
@EnableAspectJAutoProxy //开启AOP注解功能
public class SpringConfig {
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class AccountServiceTestCase {@Autowiredprivate AccountService accountService;@Testpublic void testFindById(){Account account = accountService.findById(1);}@Testpublic void testFindAll(){List list = accountService.findAll();}
}
findAll快点,findById慢点,因为findById还要在findAll的基础上进行一次筛选
在环绕通知中可以获取到哪些数据?
说明:在前置通知和环绕通知中都可以获取到连接点方法的参数们
@Before("pt()")
public void before(JoinPoint jp) {Object[] args = jp.getArgs(); //获取连接点方法的参数们System.out.println(Arrays.toString(args));
}
@Around("pt()")
public Object around(ProceedingJoinPoint pjp) throws Throwable {Object[] args = pjp.getArgs(); //获取连接点方法的参数们System.out.println(Arrays.toString(args));Object ret = pjp.proceed();return ret;
}
说明:在返回后通知和环绕通知中都可以获取到连接点方法的返回值
@AfterReturning(value = "pt()",returning = "ret")
public void afterReturning(String ret) { //变量名要和returning="ret"的属性值一致System.out.println("afterReturning advice ..."+ret);
}
@Around("pt()")
public Object around(ProceedingJoinPoint pjp) throws Throwable {// 手动调用连接点方法,返回值就是连接点方法的返回值Object ret = pjp.proceed();return ret;
}
说明:在抛出异常后通知和环绕通知中都可以获取到连接点方法中出现的异常
@AfterThrowing(value = "pt()",throwing = "t")
public void afterThrowing(Throwable t) {//变量名要和throwing = "t"的属性值一致System.out.println("afterThrowing advice ..."+ t);
}
@Around("pt()")
public Object around(ProceedingJoinPoint pjp) {Object ret = null;//此处需要try...catch处理,catch中捕获到的异常就是连接点方法中抛出的异常try {ret = pjp.proceed();} catch (Throwable t) {t.printStackTrace();}return ret;
}
请说出我们该使用什么类型的通知来完成这个需求?
需求:对百度网盘分享链接输入密码时尾部多输入的空格做兼容处理
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6iiXd4j9-1679148305925)(assets/image-20210731193059709.png)]
分析:
①:在业务方法执行之前对所有的输入参数进行格式处理——trim()
②:使用处理后的参数调用原始方法——环绕通知中存在对原始方法的调用
//-------------service层代码-----------------------
public interface ResourcesService {public boolean openURL(String url ,String password);
}
@Service
public class ResourcesServiceImpl implements ResourcesService {@Autowiredprivate ResourcesDao resourcesDao;public boolean openURL(String url, String password) {return resourcesDao.readResources(url,password);}
}
//-------------dao层代码-----------------------
public interface ResourcesDao {boolean readResources(String url, String password);
}
@Repository
public class ResourcesDaoImpl implements ResourcesDao {public boolean readResources(String url, String password) {System.out.println(password.length());//模拟校验return password.equals("root");}
}
@Component
@Aspect
public class DataAdvice {@Pointcut("execution(boolean com.itheima.service.*Service.*(*,*))")private void servicePt(){}@Around("DataAdvice.servicePt()")public Object trimStr(ProceedingJoinPoint pjp) throws Throwable {Object[] args = pjp.getArgs();for (int i = 0; i < args.length; i++) {//判断参数是不是字符串if(args[i].getClass().equals(String.class)){args[i] = args[i].toString().trim();}}Object ret = pjp.proceed(args);return ret;}
}
@Configuration
@ComponentScan("com.itheima")
@EnableAspectJAutoProxy
public class SpringConfig {
}
public class App {public static void main(String[] args) {ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);ResourcesService resourcesService = ctx.getBean(ResourcesService.class);boolean flag = resourcesService.openURL("http://pan.baidu.com/haha", "root ");System.out.println(flag);}
}
切入点表达式标准格式:动作关键字(访问修饰符 返回值 包名.类/接口名.方法名(参数)异常名)
切入点表达式描述通配符:
切入点表达式书写技巧
1.按标准规范开发
2.查询操作的返回值建议使用*匹配
3.减少使用…的形式描述包
4.对接口进行描述,使用*表示模块名,例如UserService的匹配描述为*Service
5.方法名书写保留动词,例如get,使用*表示名词,例如getById匹配描述为getBy*
6.参数根据实际情况灵活调整