一、概述
AOP的实现方法在上两篇博客中已经用了两种方法来实现如今的问题来了尽管我们利用AOP,那么client怎样信息传递?利用JoinPoint接口来实现client给详细实现类的传递參数。
二、代码演示。
文件夹结构:
SecurityHandler.java
package com.tgb.spring; import org.aspectj.lang.JoinPoint; public class SecurityHandler{ private void checkSecurity(JoinPoint joinPoint){ for (int i = 0; i < joinPoint.getArgs().length; i++) { System.out.println(joinPoint.getArgs()[i]); } System.out.println(joinPoint.getSignature().getName()); System.out.println("=====checkSecurity===="); } }
Client.java
package com.tgb.spring; import org.springframework.beans.factory.BeanFactory; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.tgb.spring.UserManager; public class Client { public static void main(String[] args) { BeanFactory factory=new ClassPathXmlApplicationContext("applicationContext.xml"); UserManager userManager=(UserManager) factory.getBean("userManager"); userManager.addUser("张三", "123"); //userManager.delUser(1); } }
UserManager.java
package com.tgb.spring; public interface UserManager { public void addUser(String username,String password); public void delUser(int userId); public String findUserById(int userId); public void modifyUser(int userId,String username,String password); }
UserManagerImpl.java
package com.tgb.spring; public class UserManagerImpl implements UserManager { public void addUser(String username, String password) { //checkSecurity(); System.out.println("===UserManager.addUser==="); } public void delUser(int userId) { //checkSecurity(); System.out.println("===UserManager.delUser==="); } public String findUserById(int userId) { //checkSecurity(); System.out.println("===UserManager.findUserById==="); return "张三"; } public void modifyUser(int userId, String username, String password) { //checkSecurity(); System.out.println("===UserManager.modifyUser==="); } // private void checkSecurity(){ // System.out.println("checkSecurity"); // // } }
applicationContext.xml
<?
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="userManager" class="com.tgb.spring.UserManagerImpl" /> <bean id="securityHandler" class="com.tgb.spring.SecurityHandler"/> <aop:config> <aop:aspect id="securityAspect" ref="securityHandler"> <aop:pointcut id="addAddMethod" expression="execution(* com.tgb.spring.*.*(..))" /> <aop:before method="checkSecurity" pointcut-ref="addAddMethod" /> </aop:aspect> </aop:config> </beans>
效果图:
三、总结。
我们能够通过Advice中加入一个JoinPoint參数,这个值会由spring自己主动传入。从JoinPoint中能够取得。