Skip to content

Instantly share code, notes, and snippets.

@naffan2014
Created May 9, 2019 02:55
Show Gist options
  • Save naffan2014/dcbf692749f7f46bee595391deae6686 to your computer and use it in GitHub Desktop.
Save naffan2014/dcbf692749f7f46bee595391deae6686 to your computer and use it in GitHub Desktop.
学习切面编程的例子,作为解释用,并没有把所有的依赖文件放上来

#工厂类

把实现接口的类扔进代理中,代理去增加扩展功能,这样就实现了切面编程。好处是没有继承,也就是说没有依赖关系,降低了耦合度,从而达到解耦的目的

public class MyBeanFactory{
    public static IUserService createUserService(){
        final IUserService userService = new UserServiceImpl();
        final MyAspect aspect = new MyAspect;
        
        IUserService proxyService = (IUserService)Proxy.newProxyInstance(
            MyBeanFactory.class.getClassLoader, //类加载器
            userService.getClass().getInterface(), //期望哪个对象的接口被拦截
            new InvocationHandler(){
                @Override
                public Object invoke(Object proxy,Method method,Objectp[] args)
                    throws Throwable{ 
                        aspect.before();
                        Object retObj = method.invoke(userService,args);//利用反射
                        aspect.after();
                        return retObj; //应该是业务方法的返回值
                    }
            }
        )
    }
    return proxyService;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment