流程切面

/ Spring / 没有评论 / 346浏览

我们创建一个UserServiceFactory,在这个类中调用UserService类中的方法。具体代码如下:

public class UserServiceFactory {

private UserService userService;

public void service(String username, String nickName, String password) {
userService.register(username, nickName, password);
userService.login(username, password);
}

public void setUserService(UserService userService) {
this.userService = userService;
}
}

如果我们希望所有调用UserServiceFactory类的service方法时,都织入增强时,我们就要使用流程切面了。

<bean id="userServiceTarget" class="com.jilinwula.spring.aop.UserService"/>
<bean id="userServiceBeforeAdvice" class="com.jilinwula.spring.aop.UserServiceBeforeAdvice"/>
<bean id="controlFlowPointcut" class="org.springframework.aop.support.ControlFlowPointcut">
<constructor-arg type="java.lang.Class" value="com.jilinwula.spring.aop.UserServiceFactory"/>
<constructor-arg type="java.lang.String" value="service"/>
</bean>
<bean id="pointcutAdvisor" class="org.springframework.aop.support.DefaultPointcutAdvisor"
p:pointcut-ref="controlFlowPointcut"
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
spring增强: login
开启事物
用户登陆: username: admin password: jilinwula