JDK实现动态代理需要实现类通过接口定义业务方法,对于没有接口的类,如何实现动态代理呢?
这就需要CGLib了。CGLib采用了非常底层的字节码技术,其原理是通过字节码技术为一个类创建子类,并在子类中采用方法拦截的技术拦截所有父类方法的调用,顺势织入横切逻辑。
JDK动态代理与CGLib动态代理均是实现Spring AOP的基础。
一、JDK这种方式动态代理
1. 没引入spring配置文件时,怎么实现JDK动态代理
情景介绍:如何解决全站中文乱码问题?
我们会定义一个过滤器:CharacterEncodingFilter
[java] view plaincopyprint?
- package cn.xym.empmis.web.filter;
-
- import java.io.IOException;
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Method;
- import java.lang.reflect.Proxy;
-
- import javax.servlet.Filter;
- import javax.servlet.FilterChain;
- import javax.servlet.FilterConfig;
- import javax.servlet.ServletException;
- import javax.servlet.ServletRequest;
- import javax.servlet.ServletResponse;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
-
-
-
-
-
-
- public class CharacterEncodingFilterimplements Filter{
-
- @Override
- public void init(FilterConfig filterconfig)throws ServletException {
-
-
- }
-
- @Override
- public void doFilter(ServletRequest servletrequest,
- ServletResponse servletresponse, FilterChain filterchain)
- throws IOException, ServletException {
-
-
- final HttpServletRequest request = (HttpServletRequest) servletrequest;
- HttpServletResponse response = (HttpServletResponse) servletresponse;
- request.setCharacterEncoding("UTF-8");
-
-
-
- filterchain.doFilter((ServletRequest) Proxy.newProxyInstance(CharacterEncodingFilter.class.getClassLoader()
- , request.getClass().getInterfaces()
- , new InvocationHandler() {
-
- @Override
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
-
-
-
- if (!method.getName().equals("getParameter")){
- return method.invoke(request, args);
- }
- if (!request.getMethod().equalsIgnoreCase("get")){
- return method.invoke(request, args);
- }
-
- String value = http://www.mamicode.com/(String) method.invoke(request,args); >
- if (value =http://www.mamicode.com/=>null){
- returnnull;
- }
- returnnew String(value.getBytes("iso8859-1"),"UTF-8");
- }
- }), response);
- }
- @Override
- public void destroy() {
-
-
- }
-
- }
package cn.xym.empmis.web.filter;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 解决全站乱码问题
* @author Administrator
*
*/
public class CharacterEncodingFilter implements Filter{
@Override
public void init(FilterConfig filterconfig) throws ServletException {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest servletrequest,
ServletResponse servletresponse, FilterChain filterchain)
throws IOException, ServletException {
final HttpServletRequest request = (HttpServletRequest) servletrequest;
HttpServletResponse response = (HttpServletResponse) servletresponse;
request.setCharacterEncoding("UTF-8"); //只能解决Post方式提交的乱码问题,无法解决get提交的乱码
//可以用包装设计模式,也可以用动态代理技术来解决get请求的乱码问题
filterchain.doFilter((ServletRequest) Proxy.newProxyInstance(CharacterEncodingFilter.class.getClassLoader()
, request.getClass().getInterfaces()
, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
//proxy表示:动态代理对象
//method表示:需要代理的方法
//args表示需要代理方法的参数
if (!method.getName().equals("getParameter")){
return method.invoke(request, args);
}
if (!request.getMethod().equalsIgnoreCase("get")){
return method.invoke(request, args);
}
//满足要拦截处理的条件了
String value = http://www.mamicode.com/(String) method.invoke(request,args);>
2.引入spring配置文件时,实现JDK动态代理功能
要设计出几种需要的“通知类型”的类,在配置文件中配置代理对象,指定代理目标(即要被代理的对象),指定所有要代理的接口(列表),最后把需要的“通知类型”织入到代理对象!
[html] view plaincopyprint?
- <?xmlversion="1.0"encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:tx="http://www.springframework.org/schema/tx"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
- http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
-
-
- <beanid="userServiceImpl"class="cn.cubic.aop.service.impl.UserServiceImpl"/>
-
-
-
- <beanid="myMethodBeforeAdvice"class="cn.cubic.aop.MyMethodBeforeAdvice"/>
-
- <beanid="myAfterReturningAdvice"class="cn.cubic.aop.MyAfterReturningAdvice"/>
-
- <beanid="myMethodInterceptor"class="cn.cubic.aop.MyMethodInterceptor"/>
-
- <beanid="myThrowsAdvice"class="cn.cubic.aop.MyThrowsAdvice"/>
-
-
- <beanid="myMethodBeforeAdviceFilter"class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor">
- <propertyname="advice"ref="myMethodBeforeAdvice"/>
- <propertyname="mappedNames">
- <list>
- <value>sayHello</value>
- </list>
- </property>
- </bean>
-
-
-
- <beanid="proxyFactoryBean"class="org.springframework.aop.framework.ProxyFactoryBean">
-
-
- <propertyname="target"ref="userServiceImpl"/>
-
-
- <propertyname="proxyInterfaces">
- <list>
- <value>cn.cubic.aop.service.IAbstractService</value>
- <value>cn.cubic.aop.service.IAbstractService2</value>
- </list>
- </property>
-
-
- <propertyname="interceptorNames">
- <list>
- <value>myMethodBeforeAdviceFilter</value>
- <value>myAfterReturningAdvice</value>
- <value>myMethodInterceptor</value>
- <value>myThrowsAdvice</value>
- </list>
- </property>
- </bean>
-
- </beans>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<!-- 准备要做为目标对象(被代理对象) -->
<bean id="userServiceImpl" class="cn.cubic.aop.service.impl.UserServiceImpl" />
<!-- 配置通知对象 -->
<!-- 前置通知 -->
<bean id="myMethodBeforeAdvice" class="cn.cubic.aop.MyMethodBeforeAdvice"/>
<!-- 后置通知 -->
<bean id="myAfterReturningAdvice" class="cn.cubic.aop.MyAfterReturningAdvice" />
<!-- 环绕通知 -->
<bean id="myMethodInterceptor" class="cn.cubic.aop.MyMethodInterceptor" />
<!-- 异常通知 -->
<bean id="myThrowsAdvice" class="cn.cubic.aop.MyThrowsAdvice"/>
<!-- 引入通知 ,自定义切入点,了解即可-->
<bean id="myMethodBeforeAdviceFilter" class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor">
<property name="advice" ref="myMethodBeforeAdvice"/>
<property name="mappedNames">
<list>
<value>sayHello</value>
</list>
</property>
</bean>
<!-- 配置代理对象 -->
<bean id="proxyFactoryBean" class="org.springframework.aop.framework.ProxyFactoryBean">
<!-- 指定你希望代理的目标对象 -->
<property name="target" ref="userServiceImpl" />
<!-- 指定“代理接口”的列表 -->
<property name="proxyInterfaces">
<list>
<value>cn.cubic.aop.service.IAbstractService</value>
<value>cn.cubic.aop.service.IAbstractService2</value>
</list>
</property>
<!-- 把“通知”织入代理对象 -->
<property name="interceptorNames">
<list>
<value>myMethodBeforeAdviceFilter</value>
<value>myAfterReturningAdvice</value>
<value>myMethodInterceptor</value>
<value>myThrowsAdvice</value>
</list>
</property>
</bean>
</beans>
二、CGlib 这种方式实现动态代理
CGLIBProxy类:
[java] view plaincopyprint?
- package cn.cubic.aop.cglib;
-
- import java.lang.reflect.Method;
-
- import net.sf.cglib.proxy.Enhancer;
- import net.sf.cglib.proxy.MethodInterceptor;
- import net.sf.cglib.proxy.MethodProxy;
-
-
-
-
-
-
- public class CGLIBProxyimplements MethodInterceptor{
-
- private Enhancer enhancer = new Enhancer();
-
- public Object getProxy(Class clazz){
-
-
- enhancer.setSuperclass(clazz);
- enhancer.setCallback(this);
-
-
- return enhancer.create();
- }
-
-
-
- @Override
- public Object intercept(Object obj, Method method, Object[] args,
- MethodProxy methodproxy) throws Throwable {
-
- System.out.println("cglib实现的前置代理");
-
-
- Object result = methodproxy.invokeSuper(obj, args);
-
- System.out.println("cglib实现的后置代理");
- return result;
- }
-
-
- }
package cn.cubic.aop.cglib;
import java.lang.reflect.Method;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
/**
*
* Simple to Introduction
*
* @ProjectName: [springAop]
* @Package: [cn.cubic.aop.cglib]
* @ClassName: [CGLIBProxy]
* @Description: [描述该类的功能]
* @Author: [逍遥梦]
* @CreateDate: [2014-3-1 下午4:47:22]
* @UpdateUser: [逍遥梦]
* @UpdateDate: [2014-3-1 下午4:47:22]
* @UpdateRemark: [说明本次修改内容]
* @Version: [v1.0]
*
*/
public class CGLIBProxy implements MethodInterceptor{
private Enhancer enhancer = new Enhancer();
public Object getProxy(Class clazz){
//设置父类
enhancer.setSuperclass(clazz);
enhancer.setCallback(this);
//通过字节码技术动态创建子类实例
return enhancer.create();
}
/**
* 所有的方法都会被这个方法所拦截。该类实现了创建子类的方法与代理的方法。getProxy(SuperClass.class)方法通过入参即父类的字节码,通过扩展父类的class来创建代理对象。intercept()方法拦截所有目标类方法的调用,obj表示目标类的实例,method为目标类方法的反射对象,args为方法的动态入参,proxy为代理类实例。
*/
@Override
public Object intercept(Object obj, Method method, Object[] args,
MethodProxy methodproxy) throws Throwable {
System.out.println("cglib实现的前置代理");
//通过代理类调用父类中的方法
Object result = methodproxy.invokeSuper(obj, args);
System.out.println("cglib实现的后置代理");
return result;
}
}
CGLIBUserServiceImpl类:
[java] view plaincopyprint?
- package cn.cubic.aop.service.impl;
-
- public class CGLIBUserServiceImpl {
-
- public void sayHello(){
- System.out.println("CGLIBUserServiceImpl的sayHello方法被调用!");
- }
-
- public void sayBye(){
- System.out.println("CGLIBUserServiceImpl的sayHello方法被调用!");
- }
- }
package cn.cubic.aop.service.impl;
public class CGLIBUserServiceImpl {
public void sayHello(){
System.out.println("CGLIBUserServiceImpl的sayHello方法被调用!");
}
public void sayBye(){
System.out.println("CGLIBUserServiceImpl的sayHello方法被调用!");
}
}
Main函数:[java] view plaincopyprint?
- package cn.cubic.aop.junit;
-
- import cn.cubic.aop.cglib.CGLIBProxy;
- import cn.cubic.aop.service.impl.CGLIBUserServiceImpl;
-
- public class CGLIBTest {
-
-
-
-
- public staticvoid main(String[] args) {
-
- CGLIBProxy proxy = new CGLIBProxy();
-
-
- CGLIBUserServiceImpl impl = (CGLIBUserServiceImpl)proxy.getProxy(CGLIBUserServiceImpl.class);
- impl.sayHello();
-
- }
-
- }
package cn.cubic.aop.junit;
import cn.cubic.aop.cglib.CGLIBProxy;
import cn.cubic.aop.service.impl.CGLIBUserServiceImpl;
public class CGLIBTest {
/**
* @param args
*/
public static void main(String[] args) {
CGLIBProxy proxy = new CGLIBProxy();
//生成子类,创建代理类
CGLIBUserServiceImpl impl = (CGLIBUserServiceImpl)proxy.getProxy(CGLIBUserServiceImpl.class);
impl.sayHello();
}
}
三、比较两种方式的优缺点
CGLib创建的动态代理对象性能比JDK创建的动态代理对象的性能高不少,但是CGLib在创建代理对象时所花费的时间却比JDK多得多,所以对于单例的对象,因为无需频繁创建对象,用CGLib合适,反之,使用JDK方式要更为合适一些。同时,由于CGLib由于是采用动态创建子类的方法,对于final方法,无法进行代理!
实现动态代理的两种方式介绍+例子demo(JDK、CGlib)