一、UserService接口
<span style="font-size:18px;">package com.seven.spring.m_aop_helloworld;
public interface UserService {
void queryUsers();
void saveUser();
void deleteUser();
}</span>
二、UserServiceImpl实现类
<span style="font-size:18px;">package com.seven.spring.m_aop_helloworld;
public class UserServiceImpl implements UserService{
@Override
public void queryUsers() {
System.out.println("查询一个User");
}
@Override
public void saveUser() {
System.out.println("保存一个User");
}
@Override
public void deleteUser() {
System.out.println("删除一个User");
}
}</span>
这种是有接口的方式Spring会按照JDK动态代理的方式来实现
三、拦截方法的类LogAdvice实现了MethodInterceptor接口,
<span style="font-size:18px;">package com.seven.spring.m_aop_helloworld;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class LogAdvice implements MethodInterceptor{
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
System.out.println("==开始执行操作==");
Object res = methodInvocation.proceed();//执行原方法
System.out.println("==操作结束==");
return res;
}
}
</span>
四、测试类MainTest,在测试类中拦截了save和delete相关的方法,query相关的方法没有被拦截
<span style="font-size:18px;">package com.seven.spring.m_aop_helloworld;
import org.junit.Test;
import org.springframework.aop.Advisor;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.aop.support.NameMatchMethodPointcut;
/**
* 使用编程方式实现aop
* @author Administrator
*
*/
public class MainTest {
@Test
public void test1(){
UserService userService = new UserServiceImpl();
//1.声明切入点,表示要拦截哪些方法
NameMatchMethodPointcut pointcut = new NameMatchMethodPointcut();
pointcut.addMethodName("save*");
pointcut.addMethodName("delete*");
//2.声明一个通知,表示拦截到之后要做什么事
LogAdvice logAdvice = new LogAdvice();
//3.组装一个切面(切面=切入点+通知)
Advisor advisor = new DefaultPointcutAdvisor(pointcut, logAdvice);
//4.为原对象生成一个代理对象
ProxyFactory proxyFactory = new ProxyFactory();
proxyFactory.addAdvisor(advisor);//添加一个切面
proxyFactory.setTarget(userService);//指定目标对象0
userService = (UserService) proxyFactory.getProxy();//得到一个代理对象
//=========================
//使用的是代理对象
userService.saveUser();
System.out.println("--------------");
userService.queryUsers();
System.out.println("--------------");
userService.deleteUser();
}
}
</span>