SpringAOP基于xml的动态代理配置
SpringAOP基于xml的动态代理配置
学习于黑马程序员Spring教程
项目结构
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4iizmu51-1596815540432)(image.png)]
接口
package com.dyf.service; /** * 账户打业务层接口 */ public interface IAccountService { /** * 模拟保存账户 */ void saveAccount(); /** * 模拟更新账户 * @param i */ void updateAccount(int i); /** * 删除账户 * @return */ int deleteAccount(); }
接口实现类
package com.dyf.service.impl; import com.dyf.service.IAccountService; /** *账户打业务层实现类 * @author DYF */ public class AccountServiceImpl implements IAccountService { @Override public void saveAccount() { System.out.println("执行了保存"); } @Override public void updateAccount(int i) { System.out.println("执行了更新"); } @Override public int deleteAccount() { System.out.println("执行了删除"); return 0; } }
增强方法
package com.dyf.utils; /** * 用于记录日志打工具类,它里面同乐 * @author DYF */ public class Logger { /** * 用于打印日志,计划在其切入点方法执行之前执行(切入点方法就是业务层方法) */ public void printLog(){ System.out.println(); } }
bean.xml
配置步骤
spring中基于XML打AOP配置 1.把通知Bean也交给Spring来管理 2.使用aop:config标签表明开始AOP配置 3.使用aop:aspect标签表明配置切面 id:给切面听唯一标识 ref:熟悉:执行通知类bean打id 4.在aop:aspect标签内部使用对应标签莱尔配置通知类型 当前案例是让printLog方法在切入点方法之前执行,所以 前置通知aop:before:表示配置前置通知 method属性:用于指定Logger类中打那个方法是前置通知 pointcut属性:永驻定制切入点表达式,该表达式打含义指的是对业务层中的那些方法增强 切入点表达式写法: 关键字:execution(表达式) 表达式: 访问修饰符 发回执 包名.类名.方法名
<?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"> <!--配置IOC,把service对象配置进来--> <bean id="accountService" class="com.dyf.service.impl.AccountServiceImpl"></bean> <bean id="logger" class="com.dyf.utils.Logger"></bean> <!--配置AOP--> <aop:config> <!--配置切面--> <aop:aspect id="logAdvice" ref="logger"> <!--配置通知类型,并且建立通知切入点方法打关联--> <aop:before method="printLog" pointcut="execution(public void com.dyf.service.impl.AccountServiceImpl.saveAccount())"></aop:before> </aop:aspect> </aop:config> </beans>``` [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9CLbt3Nd-1596815540436)(image.png)]
上一篇:
IDEA上Java项目控制台中文乱码