模仿前面的例子,完成模拟JDBC操作
1.UserDAO接口,具有insert(String name)方法,UserDAOImpl实现它
2. 用前置增强,在插入之前,完成数据库连接、事务创建工作
3.用后置增强,在插入之后,完成事务提交,数据库连接关闭操作
3. 用环绕增强,显示提示信息,前后分别为“用户等待插入”, “用户插入操作完成”
首先我们编写一个UserDao接口,这个接口中拥有insert(String name)方法,UserDaoImpl实现它
| public interface UserDAO { |
| void insert(String name); |
| } |
| |
| public class UserDaoImpl implements UserDAO{ |
| @Override |
| public void insert(String name) { |
| System.out.println(name + "添加成功。。。。。。。"); |
| } |
| } |
| |
创建一个自己的增强类
| |
| |
| |
| public class Advice { |
| |
| |
| public void before(){ |
| System.out.println("数据库的连接"); |
| System.out.println("事务创建成功"); |
| } |
| |
| |
| public void after(){ |
| System.out.println("事务提交"); |
| System.out.println("数据库连接关闭"); |
| } |
| |
| |
| public void around(ProceedingJoinPoint pt) throws Throwable { |
| |
| System.out.println("用户等待插入"); |
| |
| pt.proceed(); |
| |
| |
| System.out.println("用户插入操作完成"); |
| } |
| } |
| |
配置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"> <!-- bean definitions here --> |
| |
| <!-- 1配置对象 --> |
| |
| <bean id="userDaoImpl" class="com.pp.dao.UserDaoImpl"/> |
| <bean id="Advice" class="com.pp.service.Advice"/> |
| <!-- 2配置aop的操作 --> |
| <aop:config> |
| <!-- 2.1配置切入点被增强类--> |
| <aop:pointcut id="pointcut1" expression="execution(* com.pp.dao.UserDaoImpl.*(..))" /> |
| <!-- 2.2配置切面 把增强用到方法上面 --> |
| <aop:aspect ref="Advice"> |
| <!-- 配置增强类 |
| method: 增强类里面使用哪个方法作为前置 |
| pointcut-ref 把before1增强要用到哪个切入点上--> |
| <aop:before method="before" pointcut-ref="pointcut1"/> |
| <aop:after-returning method="after" pointcut-ref="pointcut1"/> |
| <aop:around method="around" pointcut-ref="pointcut1"/> |
| </aop:aspect> |
| </aop:config> |
| </beans> |
| |
编写测试类
| @Test |
| public void test_springAop(){ |
| ApplicationContext context = new ClassPathXmlApplicationContext("beans_03.xml"); |
| UserDAO userDaoImpl = context.getBean("userDaoImpl", UserDAO.class); |
| userDaoImpl.insert("盼盼"); |
| } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南