[刘阳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();
}
原文地址:https://www.cnblogs.com/liuyangjava/p/6680319.html