这是我要实现的效果
public static void main(String[] args) { UserDao proxy = (UserDao) BeanProxyFactory.getProxyObject(UserDaoImpl.class.getName()); proxy.save(new User());//我想实现保存的时候,自动调用一些动作 }
看代码
package org.dao; import org.pojo.User; public interface UserDao { public void save(User user); public void update(User user); }
package org.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(value = RetentionPolicy.RUNTIME) public @interface Transaction { }
package org.dao.impl; import org.annotation.Transaction; import org.dao.UserDao; import org.pojo.User; @Transaction public class UserDaoImpl implements UserDao { public void save(User user) { System.out.println("save user!" + user.getUserId()); } public void update(User user) { System.out.println("save user!" + user.getUserId()); } }
package org.aop; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.util.HashSet; import java.util.Set; import org.annotation.Transaction; public class MethodInvocationHandler implements InvocationHandler { private Object originalObject; private Set<String> transactionMethod = new HashSet<String>(); @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object result = null; if (transactionMethod.contains(method.getName())) { System.out.println("事务开启"); result = method.invoke(originalObject, args); System.out.println("事务结束"); } else { result = method.invoke(originalObject, args); } return result; } public MethodInvocationHandler(Object originalObject) { this.originalObject = originalObject; for (Method m : originalObject.getClass().getMethods()) { if (m.isAnnotationPresent(Transaction.class) || originalObject.getClass().isAnnotationPresent( Transaction.class)) { this.transactionMethod.add(m.getName()); } } } }
package org.aop; import java.lang.reflect.Proxy; import org.dao.UserDao; import org.dao.impl.UserDaoImpl; import org.pojo.User; public class BeanProxyFactory { public static Object getProxyObject(String className) { Object proxyObject = null; try { Class claszz = Class.forName(className); MethodInvocationHandler handler = new MethodInvocationHandler( claszz.newInstance()); proxyObject = Proxy.newProxyInstance(claszz.getClassLoader(), claszz.getInterfaces(), handler); } catch (Exception e) { } return proxyObject; } public static void main(String[] args) { UserDao proxy = (UserDao) BeanProxyFactory .getProxyObject(UserDaoImpl.class.getName()); proxy.save(new User());// 我想实现保存的时候,自动调用一些动作 } }