程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> Spring代理處理參數和方法

Spring代理處理參數和方法

編輯:關於JAVA

Spring代理處理參數和方法:

package com.rx.spring.dynamicmock;
public interface UserManager {
  public void addUser(String username, String password);
  public void deleteUser(int id);
}
package com.rx.spring.dynamicmock;
public class UserManagerImpl implements UserManager {
  public void addUser(String username, String password) {
    System.out.println("-------UserManagerImpl.addUser()----------");
  }
  public void deleteUser(int id) {
    System.out.println("-------UserManagerImpl.deleteUser()----------");
  }
}
package com.rx.spring.dynamicmock;
import org.aspectj.lang.JoinPoint;
public class SecurityHandler {
  /***
   * 處理連接點
   * @param joinPoint 
   */
  private void checkSecurity(JoinPoint joinPoint) {
    Object[] args = joinPoint.getArgs();
    for (int i=0; i<args.length; i++) {
      System.out.println(args[i]);
    }
    System.out.println(joinPoint.getSignature().getName());
    System.out.println("----------checkSecurity()---------------");
  }
}
package com.rx.spring.dynamicmock;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Client {
  public static void main(String[] args) {
    BeanFactory factory = new ClassPathXmlApplicationContext("applicationContextMockSpring.xml");
    UserManager userManager = (UserManager)factory.getBean("userManager");
    userManager.addUser("abc", "123");
  }
}

<?xml version="1.0" encoding="UTF-8"?>
<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"
     xmlns:tx="http://www.springframework.org/schema/tx"
     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
      http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
      http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
  <bean id="securityHandler" class="com.rx.spring.dynamicmock.SecurityHandler"/>
  <bean id="userManager" class="com.rx.spring.dynamicmock.UserManagerImpl"/>
  <aop:config>
    <aop:aspect id="security" ref="securityHandler">
      <aop:pointcut id="allAddMethod" expression="execution(* com.rx.spring.dynamicmock.UserManagerImpl.add*(..))"/>
      <aop:before method="checkSecurity" pointcut-ref="allAddMethod"/>
    </aop:aspect>
  </aop:config>
</beans>
運行結果:

abc
123
addUser
----------checkSecurity()---------------
-------UserManagerImpl.addUser()----------

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved