spring的AOP是面向切面编程的意思,不需要改变原有代码的基础上对原有代码进行增强
我们来看入门案例
首先创建一个service接口
package com.lp.service;
/**
* @Date 2020/5/29 14:37
* @Author luopeng
*/
public interface AccountService {
/**
* 模拟保存账户
*/
void saveAccount();
/**
* 模拟更新账户
*/
void updateAccount();
/**
* 模拟删除账户
*/
void deleteAccount(int id);
}
然后是它的实现类
package com.lp.service.impl;
import com.lp.service.AccountService;
/**
* @Date 2020/5/29 14:40
* @Author luopeng
*/
public class AccountServiceImpl implements AccountService {
public void saveAccount() {
System.out.println("执行了保存!");
}
public void updateAccount() {
System.out.println("执行了更新!");
}
public void deleteAccount(int id) {
System.out.println("执行了删除!"+id);
}
}
接下来我们将对service中的方法进行增强操作,我们写一个工具类来模拟操作
package com.lp.utils;
/**
* 用于记录日志的工具类,它里面提供了公共方法
*
* @Date 2020/5/29 14:41
* @Author luopeng
*/
public class Logger {
/**
* 用于打印日志,计划让其在切入点方法执行前执行(切入点方法就是service业务层的代码)
*/
public void printLog(){
System.out.println("Logger类里面的printLog开始日志输入。。。");
}
}
接下来要写xml配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- spring配置ioc-->
<bean id="accountService" class="com.lp.service.impl.AccountServiceImpl"/>
<!-- spring中基于xml的aop配置
把通知bean也交给spring来管理
使用aop:config标签表明开始AOP配置
使用aop:aspect标签表明配置切面
在aop:aspect标签的内部使用对应的标签来配置通知的类型,
现在的实例是让printLog方法在切入点方法执行之前执行,
所以是迁前置通知
aop:before 表示配置前置通知
切入点表达式: 访问修饰符 返回值类型 包名 类名 方法名()
public void com.lp.service.AccountService.saveAccount()
其中访问修饰符可以省略
全通配写法:
* *..*.*(..)
方法里面*表示有参数才匹配的意思,
方法里的..表示有参数无参数都匹配的意思,不写即表示无参数
实际开发中切入点表达式的通常写法:
* com.lp.service.impl.*.*(..)
-->
<bean id="logger" class="com.lp.utils.Logger"/>
<aop:config>
<aop:aspect id="logAdvice" ref="logger">
<aop:before method="printLog" pointcut="execution(* com.lp.service.impl.*.*(..))"></aop:before>
</aop:aspect>
</aop:config>
</beans>
随手写一个测试类测试一下
package com.lp.test;
import com.lp.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @Date 2020/5/29 15:06
* @Author luopeng
*/
public class AOPTest {
public static void main(String[] args) {
ApplicationContext bean = new ClassPathXmlApplicationContext("bean.xml");
AccountService accountService = bean.getBean("accountService", AccountService.class);
accountService.saveAccount();
accountService.deleteAccount(1);
accountService.updateAccount();
}
}
执行结果如下
上面我们只写了一种通知类型,下一篇通知类型我会记我学习通知类型的笔记!