CGLIB (Code Generation Library) 是一个动态字节码生成库, 基于ASM, 使用时需要asm.jar。(Groovy也是使用ASM来生成java的字节码)
使用java的java.lang.reflect.Proxy只能针对接口生成代理; 而使用CGLIB则可以针对类生成代理. CGLIB原理是在运行时动态生成一个被代理类的子类。
下面的例子使用CGLIB, 对服务层对象的方法进行拦截,实现一个类似的AOP.
- public class ProductService implements ServiceInterface<ProductDTO> {
- public void doDelete(Integer id) {
- productDAO.delete(id);
- }
- public void doSave(ProductDTO dto) {
- productDAO.saveOrUpdate(dto);
- }
- public void doUpdate(ProductDTO dto) {
- productDAO.saveOrUpdate(dto);
- }
- public ProductDTO getObject(Integer id) {
- return productDAO.getProduct(id);
- }
- }
ProductService是一个简单的服务层类, 在ServiceInterface中定义了DAO对象和一些方法。
如果服务层对象有事物方面的需要, 就使用Interceptor来增强. 需要实现 net.sf.cglib.proxy.MethodInterceptor 接口.
- public class ServiceMethodInterceptor implements MethodInterceptor {
- private static final Logger logger = Logger.getLogger(ServiceMethodInterceptor.class);
- public Object intercept(Object o, Method method, Object[] args, MethodProxy proxy) throws Throwable {
- if (method == null || StringUtils.isBlank(method.getName())) {
- logger.error("Method is null!");
- return null;
- }
- String methodName = method.getName();
- //所有以do开头的方法,使用updateTransaction
- if (methodName.startsWith("do")) {
- return updateTransaction(o, method, args, proxy);
- }
- //所有以get开头的方法,使用queryTransaction
- if (methodName.startsWith("get")) {
- return queryTransaction(o, method, args, proxy);
- }
- return proxy.invokeSuper(o,args);
- }
- private Object queryTransaction(Object o, Method method, Object[] args, MethodProxy proxy) throws Throwable {
- Object result = null;
- try{
- result = proxy.invokeSuper(o,args);
- } catch (Exception e) {
- logger.fatal(e);
- } finally {
- TransactionBO.endSession();
- }
- return result;
- }
- private Object updateTransaction(Object o, Method method, Object[] args, MethodProxy proxy) throws Throwable {
- Object result = null;
- try{
- TransactionBO.beginTransaction();
- result = proxy.invokeSuper(o,args);
- TransactionBO.commit();
- } catch (Exception e) {
- TransactionBO.rollback();
- } finally {
- TransactionBO.endSession();
- }
- return result;
- }
- }
- public class ServiceFactory {
- public static <T extends ServiceInterface> T getServiceInstance(Class<T> clazz) {
- Enhancer enhancer = new Enhancer();
- enhancer.setSuperclass(clazz);
- enhancer.setCallback(new ServiceMethodInterceptor());
- return (T) enhancer.create();
- }
- }
使用ProductService时,需要由ServiceFactory创建
- public static void main(String[] args) {
- ProductService productService = ServiceFactory.getServiceInstance(ProductService.class);
- productService.doSave(...);
- productService.getObject(...);
- }
实际上这里使用的是CGLIB生成的ProductService的子类. Enhancer生成的子类都实现了net.sf.cglib.proxy.Factory接口, 可以通过Factory.getCallbacks()取回MethodInterceptor
参考
http://www.iteye.com/topic/98178
http://www.blogjava.net/calvin/archive/2005/11/28/21741.html
http://www-128.ibm.com/developerworks/cn/java/j-dyn0414/index.html