spring 对AOP的支持 从JoinPoint得到相关信息
package zhc.love.dj.test; public interface UserManger { public void addUser(String name,String password); public void delUser(int id) ; public void modUser(int id,String name,String password); }
package zhc.love.dj.test; public class UserMangerImp implements UserManger { public void addUser(String name, String password) { System.out.println("==============UserMangerImp.addUser()==================="); } public void delUser(int id) { System.out.println("==============UserMangerImp.delUser()==================="); } public void modUser(int id, String name, String password) { System.out.println("==============UserMangerImp.modUser()==================="); } }
package zhc.love.dj.test; import org.aspectj.lang.JoinPoint; public interface MySecurtyManger { public void checkSecurity(JoinPoint joinPoint); }
package zhc.love.dj.test; import org.aspectj.lang.JoinPoint; public class MySecurtyMangerImp implements MySecurtyManger { //可以通过在通知中加入一个JoinPoint参数,这个参数Srping会自动传入,我们从joinPoint //中可以获得目标对象的相关信息,,如参数,方法名 public void checkSecurity(JoinPoint joinPoint) { System.out.println("joinPoint =" + joinPoint.getSignature().getName()); Object[] args = joinPoint.getArgs(); for(int i=0;i<args.length;i++){ System.out.println(args[i]); } System.out.println("=========checkSecurity()========="); } }
package zhc.love.dj.test; import org.springframework.beans.factory.BeanFactory; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Client { public static void main(String[] args) { //用spring的类来加载配置文件 BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml"); //通过工厂产生类 调用对应类的id UserManger mangaer = (UserManger)factory.getBean("UserManger"); mangaer.addUser("zhang", "jingjing"); // mangaer.delUser(1); } }
<?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" 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"> <!-- 采用配置方式静态进行aop--> <aop:config> <aop:aspect id="MySecurty" ref="MySecurtyMangerImp"> <aop:pointcut id="allAddMethod" expression="execution(* add*(..))||execution(* del*(..))" /> <aop:before pointcut-ref="allAddMethod" method="checkSecurity"/> </aop:aspect> </aop:config> <bean id="MySecurtyMangerImp" class="zhc.love.dj.test.MySecurtyMangerImp"></bean> <bean id="UserManger" class="zhc.love.dj.test.UserMangerImp"></bean> </beans>