[刘阳Java]_Spring AOP基于XML配置介绍_第9讲

基于注解配置的Spring AOP固然简单,但是这节我们会给大家介绍基于XML配置的AOP是如何应用的。为什么这么说了,因为后面我们还会介绍到Spring对Dao操作的事务管理(基于AOP的XML文件方式来配置事务)

1. 基于XML文件方式来配置Spring的AOP,则我们需要的一些基本元素如下

  • <aop:config.../>,此标签很重要。它是在XML里配置AOP功能的核心标签
    • all aspect and advisor elements must be placed within an <aop:config> element
    • An <aop:config> element can contain pointcut, advisor, and aspect elements
  • 如果要使用<aop:config…/>一定要把AOP中一些俗语和概念搞懂【很重要】

2. 来看一个案例就能很直观地了解到基于XML配置的AOP是如何应用的呢

  • 创建LogAopXML的切面
复制代码
package com.spring.aop;

import java.util.Date;

public class LogAopXML {

 public void logBefore() {
    System.out.println("==基于XML的AOP前置建议==" + new Date());
 }
}
复制代码
  • 创建bean-aop-xml.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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
 http://www.springframework.org/schema/aop
 http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

<aop:config>
    <aop:aspect id="myAspect" ref="logAopXML">
        <aop:pointcut expression="execution(* com.spring.dao.impl.TeacherDaoImpl.*(..))" id="businessService"/>
        <aop:before pointcut-ref="businessService" method="logBefore"></aop:before>
    </aop:aspect>
</aop:config>

<bean id="teacherService" class="com.spring.services.TeacherService">
    <property name="dao" ref="teacherDao"></property>
</bean>
<bean id="teacherDao" class="com.spring.dao.impl.TeacherDaoImpl"></bean>
<bean id="logAopXML" class="com.spring.aop.LogAopXML"></bean>
</beans>
复制代码

上述代码中

<aop:config>,主要是配置存放切面,切入点,建议
<aop:aspect>,主要是配置切面类,一般需要制定好id,ref这两个属性
<aop:pointcut>,主要配置切入点,描述切入点规则
<aop:before>,主要配置的是前置建议

  • 通过JUnit来进行单元测试
@Test
public void testLogAopXml() {
    ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
    TeacherService ts = (TeacherService)ac.getBean("teacherService");
    ts.insert();
}

 

posted @   子墨老师  阅读(402)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
点击右上角即可分享
微信分享提示