基于xml配置方式的AOP
原创
©著作权归作者所有:来自51CTO博客作者进击的菜鸟子的原创作品,请联系作者获取转载授权,否则将追究法律责任
1. 实现步骤 115
1.1 第一步:编写目标类
package com.powernode.spring6.service;
/**
* 基于xml配置方式的AOP 115
**/
public class UserService {//目标对象
public void logout(){ //目标方法
System.out.println("系统正在安全退出...");
}
}
1.2 第二步:编写切面类,并且编写通知
package com.powernode.spring6.service;
import org.aspectj.lang.ProceedingJoinPoint;
/**
* 切面
* 基于xml配置方式的AOP 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;
/**
* 基于xml配置方式的AOP 115
* 测试
**/
public class SpringAOPTest {
@Test
public void testXml(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
UserService userService = applicationContext.getBean("userService", UserService.class);
userService.logout();
}
}