复合切点切面

/ Spring / 没有评论 / 327浏览

在前几篇中,我们所演示的事例基本都是定义的切面只有一个切点,而有时一个切点可能并满足我们的需求,例如在上一篇中流程切面的例子中,我们定义了UserServiceFactory类,在这个类中调用UserService类中的register方法和login方法。如果我们只希望增强register方法时,我们就要采用复合切切点切面了,当然我们通过一个切点也可以实现此功能,但是我们最好把这个两个不同的切点通过spring为我们提供的技术将它们结合起来,来实现我们的需求。在spring中就是通过ComposablePointcut类来实现的。下面我们看一下ComposablePointcut类的基本使用。

public class RegisterComposablePointcut {

public Pointcut getIntersectionPointcut() {
ComposablePointcut composablePointcut = new ComposablePointcut();
Pointcut pointcut = new ControlFlowPointcut(UserServiceFactory.class, "service");
NameMatchMethodPointcut matchMethodPointcut = new NameMatchMethodPointcut();
matchMethodPointcut.addMethodName("register");
return composablePointcut.intersection(pointcut).intersection((Pointcut) matchMethodPointcut);
}

}
<bean id="userServiceTarget" class="com.jilinwula.spring.aop.UserService"/>
<bean id="userServiceBeforeAdvice" class="com.jilinwula.spring.aop.UserServiceBeforeAdvice"/>
<bean id="composablePointcut" class="com.jilinwula.spring.aop.RegisterComposablePointcut"/>
<bean id="pointcutAdvisor" class="org.springframework.aop.support.DefaultPointcutAdvisor"
p:pointcut="#{composablePointcut.intersectionPointcut}"
p:advice-ref="userServiceBeforeAdvice"/>
<bean id="userService" class="org.springframework.aop.framework.ProxyFactoryBean"
p:interceptorNames="pointcutAdvisor"
p:target-ref="userServiceTarget"
p:proxyTargetClass="true"/>
@Test
public void test() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
UserService userService = applicationContext.getBean("userService", UserService.class);
UserServiceFactory userServiceFactory = new UserServiceFactory();
userServiceFactory.setUserService(userService);
userService.register("admin","吉林乌拉","jilinwula");
userService.login("admin","jilinwula");
userServiceFactory.service("admin","吉林乌拉","jilinwula");
}
用户注册: username: admin nickName: 吉林乌拉 password: jilinwula
用户登陆: username: admin password: jilinwula
spring增强: register
开启事物
用户注册: username: admin nickName: 吉林乌拉 password: jilinwula
用户登陆: username: admin password: jilinwula