Spring的AOP在集成了AspectJ后,立刻就显得方便了许多。本篇用同样的例子,来实现同样的功能。
前文提到过,@Aspect也支持完全annotation方式和XML配置的方式。为了方便比较,我这里先用XML来配置,基于上篇文章的代码。
- 添加AspectJ的dependency
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.6.12</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.12</version>
</dependency>
- 创建Aspect
@Aspect
public class MyAspect {
public void before(JoinPoint joinPoint)
{
System.out.println("Before method...");
Statistic.increaseTotalTraffic();
}
public void after(JoinPoint joinPoint)
{
System.out.println("After return...");
Statistic.increaseIncome(HALL_NAME.DINOSAUR, BigDecimal.valueOf(2l));
}
}
- 修改配置文件
- 引入aop的schema
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
- 加入aop内容
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<!-- Configure Target Objects -->
<bean id="zoo" class="com.edi.poc.Zoo">
<constructor-arg value="People"/>
</bean>
<bean id="dinoHall" class="com.edi.poc.DinoHall"/>
<bean id="jack" class="com.edi.poc.Tourer">
<constructor-arg value="Jack"/>
</bean>
<bean id="myAspect" class="com.edi.poc.aop.MyAspect"/>
<aop:config>
<aop:aspect id="customAspect" ref="myAspect">
<!-- @Before -->
<aop:pointcut id="pointcutBefore" expression="execution(* com.edi.poc.Zoo.enter(..))"/>
<aop:pointcut id="pointcutAfter" expression="execution(* com.edi.poc.ifc.Hall.visit(..))"/>
<aop:before method="before" pointcut-ref="pointcutBefore"/>
<aop:after-returning method="after" pointcut-ref="pointcutAfter"/>
</aop:aspect>
</aop:config>
</beans>
- 运行
输出
Dinosaur hall is opened.
The People Zoo is opened.
Before method...
Charge Jack $1.00 for ticket.
Jack needs to be charged first.
Dianosaur hall charges Jack $2.00
Jack visited diano hall.
After return...
Current traffic: 1
Income of DINOSAUR: ¥2.00
Dinosaur hall is closed.
The People Zoo is closed.
跟上面输出一致。
- 总结
明显看到这个实现简单明了多了。expression是个非常强大的东东,有了它,就可以避免在配置里写一堆的pointcut,advice,advisor等。
本文源码:
https://github.com/EdisonXu/POC/tree/master/intro-aop
Spring AOP @Aspect support XML
最新推荐文章于 2023-02-11 23:36:11 发布