AOP 简单案例
- 配置AOP(bean.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.itheima.service.impl.AccountServiceImpl"></bean>
<!--spring中基于AOP的XML配置步骤-->
<!--1.把通知的Bean也交给spring管理
2.使用aop:config 标签表明开始的AOP配置
3.使用aop:aspect表明配置切面
id属性:给切面提供唯一ID
ref属性:给定通知类bean的ID
4.在aop:aspect标签中配置对应标签来零四配置对应通知类
aop:before表示配置的前置通知
mothod属性:用于指定类中哪个方法是前置通知
pointcut属性,用于指定切入点表达式,该表达式的含义是对业务层中的哪些方法进行增强
切入表达式写法
关键字:execution
表达式: 访问修饰符 返回值 包名.包名...类名.方法名(参数列表)
标准写法:public void com.....类名.saveAccount()
全通配写法:* *..*.*(..)
访问修饰符可以省略、返回值可以使用通配符设置为*,表示任意返回值
包名可以使用通配符,表示任意包,有几级写几级*
包名可以使用..表示当前及子包,类名和方法名都可以使用*表示通配
参数列表:
可以直接写数据类型
基本类型直接写名称 int
引用类型写 java.lang.String
可以使用通配符表示任意类型,但必须有参数
日常开发中切入点表达式通常写法:
切到业务层实现类下的所有方法:* 包名.*.*(..)
-->
<!--配置Logger类-->
<bean id="logger" class="com.itheima.util.Logger"></bean>
<!--配置AOP-->
<aop:config>
<aop:aspect id="logAdvice" ref="logger">
<!--配置通知类名建立方法和切入方法的关联(增强saveAccount增强printLog)-->
<!--<aop:before method="printLog" pointcut="execution(public void com.itheima.service.impl.AccountServiceImpl.saveAccount())"></aop:before>-->
<aop:before method="printLog" pointcut="execution(* *..*.*(..))"></aop:before>
</aop:aspect>
</aop:config>
</beans>
业务层实现类
/**
* 账户的业务层实现类
*/
public class AccountServiceImpl implements IAccountService {
public void saveAccount() {
System.out.println("保存了账户");
}
public void updateAccount(int i) {
System.out.println("执行了更新");
}
public int deleteAccount() {
System.out.println("执行力删除");
return 0;
}
}
测试类
public class AOPTest {
public static void main(String[] args) {
// 1.获取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.获取对象
IAccountService as = (IAccountService) ac.getBean("accountService");
//3.执行方法
as.saveAccount();
as.deleteAccount();
as.updateAccount(1);
Logger方法加强类
public class Logger {
/**
* 用于打印,计划让其在切入点方法执行前执行
*
*/
public void printLog(){
System.out.println("Logger类开始记录日志了");
}
}
结果