003SpringAOP002基于XML文件使用
作者:互联网
1 业务核心类
编写业务核心类代码:
public class Calculator {
public int add(int i, int j) {
System.out.println("add...");
return i + j;
}
}
加入到IOC容器:
<bean id="calculator" class="com.service.Calculator" />
2 切面类
编写切面类代码:
public class AspectWork {
public void workBefore() {
System.out.println("WorkBefore...");
}
public void workAfter() {
System.out.println("WorkAfter...");
}
public void workAfterReturning(Object result) {
System.out.println("WorkAfterReturning...");
}
public void workAfterThrowing(Throwable exception) {
System.out.println("WorkAfterThrowing...");
}
public Object workAround(ProceedingJoinPoint joinPoint) {
Object result = null;
try {
System.out.println("workAround...WorkBefore...");
result = joinPoint.proceed(joinPoint.getArgs());
System.out.println("workAround...WorkAfterReturning...");
} catch (Throwable e) {
System.out.println("workAround...WorkAfterThrowing...");
throw new RuntimeException();
} finally {
System.out.println("workAround...WorkAfter...");
}
return result;
}
}
加入到IOC容器:
<bean id="aspectWork" class="com.aspect.AspectWork" />
3 通知方法
配置切入点表达式和通知方法:
<aop:config>
<!-- 配置切入点表达式。 -->
<aop:pointcut expression="execution(* *.*(..))" id="pointcut" />
<!-- 配置切面类和优先级。 -->
<aop:aspect ref="aspectWork" order="12">
<!-- 配置切面通知方法。 -->
<aop:before method="workBefore" pointcut-ref="pointcut" />
<aop:after method="workAfter" pointcut-ref="pointcut" />
<aop:after-returning method="workAfterReturning" returning="result" pointcut-ref="pointcut" />
<aop:after-throwing method="workAfterThrowing" throwing="exception" pointcut-ref="pointcut" />
<!--<aop:around method="workAround" pointcut-ref="pointcut" />-->
</aop:aspect>
</aop:config>
4 测试类
编写测试类代码:
public class AspectTest {
ApplicationContext ioc = new ClassPathXmlApplicationContext("application.xml");
@Test
public void test() {
Calculator calculator = ioc.getBean(Calculator.class);
calculator.add(1, 3);
}
}
标签:XML,003SpringAOP002,基于,workAround,...,System,println,public,out 来源: https://blog.csdn.net/zhibiweilai/article/details/122666775