Spring的AOP实现(1)
UserService.java
package com.qianfeng.aop01;
import java.util.List;
public interface UserService {
List getUserList();
boolean delete(int uid);
boolean update(Object user);
boolean saveUser(Object user);
}
UserServiceImpl.java
package com.qianfeng.aop01;
import java.util.List;
public class UserServiceImpl implements UserService {
@Override
public List getUserList() {
System.out.println("查找用户");
return null;
}
@Override
public boolean delete(int uid) {
System.out.println("删除用户");
return false;
}
@Override
public boolean update(Object user) {
System.out.println("修改用户");
return false;
}
@Override
public boolean saveUser(Object user) {
System.out.println("更新用户");
return false;
}
}
MyAspect.java
package com.qianfeng.aop01;
public class MyAspect {
public void Before(){
System.out.println("---Before---");
}
public void After(){
System.out.println("---After---"+'\n'+'\n');
}
}
UserFaction.java
package com.qianfeng.aop01;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class UserFaction {
public static UserService getUserServiceImpl(){
UserServiceImpl userService = new UserServiceImpl();
MyAspect aspect = new MyAspect();
Object o = Proxy.newProxyInstance(UserFaction.class.getClassLoader(), userService.getClass().getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
aspect.Before();
Object invoke = method.invoke(userService, args);
aspect.After();
return invoke;
}
});
return (UserService) o;
}
}
Aop01Text.java
package com.qianfeng.aop01;
import org.junit.Test;
public class Aop01Text {
@Test
public void text(){
UserService userServiceImpl = UserFaction.getUserServiceImpl();
userServiceImpl.delete(1);
userServiceImpl.saveUser("");
userServiceImpl.getUserList();
userServiceImpl.update("");
}
}