当前位置: 首页 > 图灵资讯 > 技术篇> 基于xml配置方式的AOP

基于xml配置方式的AOP

来源:图灵教育
时间:2023-06-13 09:26:13

1.实现步骤1151.1第一步:编写目标类别

package com.powernode.spring6.service;/** * AOPP基于xml配置模式  115 **/public class UserService {//目标对象    public void logout(){ ///目标方法        System.out.println(”系统正在安全退出...");    }}

1.2第二步:编写切面类,并编写通知

package com.powernode.spring6.service;import org.aspectj.lang.ProceedingJoinPoint;/** * 切面 * AOPP基于xml配置模式  115 **/public class TimerAspect {    // 通知    public void aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {        // 前环绕        long begin = System.currentTimeMillis();        // 目标        joinPoint.proceed();        // 后环绕        long end = System.currentTimeMillis();        System.out.println("耗时"+(end - begin)+"毫秒");    }}

1.3第三步:编写spring配置文件

<?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:context="http://www.springframework.org/schema/context"       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/context http://www.springframework.org/schema/context/spring-context.xsd                           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">    <!--纳入spring ioc-->    <bean id="userService" class="com.powernode.spring6.service.UserService"></bean>    <bean id="timerAspect" class="com.powernode.spring6.service.TimerAspect"></bean>    <!--配置aop-->    <aop:config>        <!--切点表达式-->        <aop:pointcut id="mypointcut" expression="execution(* com.powernode.spring6.service..*(..))" />        <!--切面:通知 + 切点-->        <aop:aspect ref="timerAspect">            <aop:around method="aroundAdvice" pointcut-ref="mypointcut"/>        </aop:aspect>    </aop:config></beans>

1.4测试程序:

package com.powernode.spring6.test;import com.powernode.spring6.service.UserService;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;/** * AOPP基于xml配置模式  115 * 测试 **/public class SpringAOPTest {    @Test    public void testXml(){        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");        UserService userService = applicationContext.getBean("userService", UserService.class);        userService.logout();    }}

基于xml配置方式的AOP_xml