1. 首页
  2. 乌拉客

引介增强

引介增强是一种特殊的增强,其它的增强是方法级别的增强,即只能在方法前或方法后添加增强。而引介增强则不是添加到方法上的增强, 而是添加到类方法级别的增强,即可以为目标类动态实现某个接口,或者动态添加某些方法。我们通过下面的事例演示引介增强的使用。

public class UserService{

  public void login(String username, String password) {
    System.out.println(String.format("用户登陆: username: %s password: %s", username, password));
  }

  public void register(String username, String nickName, String password) {
    System.out.println(String.format("用户注册: username: %s nickName: %s password: %s", username, nickName, password));
  }

}
public interface ITransactionMonitor {
  void setTransactionMonitor(boolean monitor);
}
public class TransactionMonitorImpl extends DelegatingIntroductionInterceptor implements ITransactionMonitor {

  private ThreadLocal<Boolean> monitors = new ThreadLocal<Boolean>();

  @Override
  public void setTransactionMonitor(boolean monitor) {
    monitors.set(monitor);
  }

  @Override
  public Object invoke(MethodInvocation mi) throws Throwable {
    Object object = null;
    if(monitors.get() !=null && monitors.get()) {
      TransactionManager.beginTransaction();
      object = super.invoke(mi);
      TransactionManager.commit();
    } else {
      super.invoke(mi);
    }
    return object;
  }
}
@Test
public void test() {
  ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
  UserService userService = applicationContext.getBean("userService", UserService.class);
  userService.register("admin","吉林乌拉","jilinwula");

  ITransactionMonitor transactionMonitor = (ITransactionMonitor) userService;
  transactionMonitor.setTransactionMonitor(true);

  userService.register("admin","吉林乌拉","jilinwula");
}
用户注册: username: admin nickName: 吉林乌拉 password: jilinwula
开启事物
用户注册: username: admin nickName: 吉林乌拉 password: jilinwula
提交事物

原创文章,作者:二十四分之七倍根号六,如若转载,请注明出处:http://jilinwula.com/329.html

发表评论

电子邮件地址不会被公开。 必填项已用*标注

联系我们

邮件:admin@jilinwula.com

QQ:923505769

 

QR code