使用JDK中的proxy技术实现AOP功能
直接上代码,需要注意的地方已经加上注释。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.proxy.service;
2
3 public interface AopService {
4 public void save();
5 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.proxy.service.impl;
2
3 import com.proxy.service.AopService;
4
5 public class AopServiceImpl implements AopService {
6
7 private String user = null;
8
9 public String getUser() {
10 return user;
11 }
12
13 public void setUser(String user) {
14 this.user = user;
15 }
16
17 public AopServiceImpl() {
18 }
19
20 public AopServiceImpl(String user) {
21 this.user = user;
22 }
23
24 @Override
25 public void save() {
26 System.out.println("调用了save()方法");
27 }
28 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.proxy.factory;
2
3 import java.lang.reflect.InvocationHandler;
4 import java.lang.reflect.Method;
5 import java.lang.reflect.Proxy;
6
7 import com.proxy.service.impl.AopServiceImpl;
8
9 public class ProxyFactory implements InvocationHandler{
10 private Object targetObject=null;
11
12
13 public Object creatObjectIntance(Object targetObject){
14 this.targetObject=targetObject;
15 //传过来的对象必须实现接口
16 //利用反射技术获取ClassLoader和interface集合
17 //最后一个参数是回调函数,我们需要在本类中实现InvocationHandler接口 然后重写invoke()方法,方法内容见下
18 return Proxy.newProxyInstance(this.targetObject.getClass().getClassLoader(), this.targetObject.getClass().getInterfaces(), this);
19 }
20
21
22 @Override
23 public Object invoke(Object proxy, Method method, Object[] args)
24 throws Throwable {
25 AopServiceImpl aopService=(AopServiceImpl) this.targetObject;
26 if(aopService.getUser()!=null){
27 //判断用户名不为空就调用方法
28 return method.invoke(this.targetObject, args);
29 }else{
30 //判断用户名为空就返回空,不调用实现类中的方法
31 return null;
32 }
33 }
34
35 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package junit.test;
2
3 import org.junit.Test;
4
5 import com.proxy.factory.ProxyFactory;
6 import com.proxy.service.AopService;
7 import com.proxy.service.impl.AopServiceImpl;
8
9
10 public class ProxyUnitTest {
11
12 @Test public void ProxyTest(){
13 ProxyFactory factory=new ProxyFactory();
14 AopService aopService=(AopService) factory.creatObjectIntance(new AopServiceImpl());
15 aopService.save();
16 }
17 }