环绕增强

/ Spring / 没有评论 / 303浏览

 通过前置增强和后置增强可以很方便的在目标方法的前后添加横切的逻辑,实际上spring还为我们提供了环绕增强,这种增强的功能就是会在目标方法的前后添加横切逻辑。下面我们通过环绕增强来实现上2篇文章中实现的功能。

public class UserServiceInterceptor implements MethodInterceptor {

@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
System.out.println("环绕增强");
TransactionManager.beginTransaction();
Object object = methodInvocation.proceed();
TransactionManager.commit();
return object;
}
}
<bean id="userServiceAround" class="com.jilinwula.spring.aop.UserServiceInterceptor"/>
<bean id="target" class="com.jilinwula.spring.aop.UserServiceImpl"/>
<bean id="userService" class="org.springframework.aop.framework.ProxyFactoryBean"
p:proxyInterfaces="com.jilinwula.spring.aop.IUserService"
p:interceptorNames="userServiceAround"
p:target-ref="target"/>
@Test
public void test() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
IUserService userService = applicationContext.getBean("userService", IUserService.class);
userService.register("admin","吉林乌拉","jilinwula");
}
环绕增强
开启事物
用户注册: username: admin nickName: 吉林乌拉 password: jilinwula
提交事物