001/**
002 * Copyright (c) 2015-2022, Michael Yang 杨福海 (fuhai999@gmail.com).
003 * <p>
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 * <p>
008 * http://www.apache.org/licenses/LICENSE-2.0
009 * <p>
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package io.jboot.aop.cglib;
017
018import com.jfinal.proxy.ProxyFactory;
019import net.sf.cglib.proxy.MethodInterceptor;
020
021import java.util.function.Function;
022
023/**
024 * JbootCglibProxyFactory 用于扩展 cglib 的代理模式
025 *
026 * <pre>
027 * 配置方法:
028 * public void configConstant(Constants me) {
029 *     ProxyManager.me().setProxyFactory(new JbootCglibProxyFactory());
030 * }
031 * </pre>
032 */
033public class JbootCglibProxyFactory extends ProxyFactory {
034
035    /**
036     * 方便在单元测试的时候,可以对任意 class 进行 Mock
037     */
038    private static Function<Class<?>, MethodInterceptor> methodInterceptor = aClass -> new JbootCglibCallback();
039
040    public static Function<Class<?>, MethodInterceptor> getMethodInterceptor() {
041        return methodInterceptor;
042    }
043
044    public static void setMethodInterceptor(Function<Class<?>, MethodInterceptor> methodInterceptor) {
045        JbootCglibProxyFactory.methodInterceptor = methodInterceptor;
046    }
047
048    @Override
049    public <T> T get(Class<T> target) {
050        try {
051            return (T) net.sf.cglib.proxy.Enhancer.create(target, methodInterceptor.apply(target));
052        } catch (Throwable e) {
053            //原始的错误,无法给出哪个类无法被创建,错误信息不够友好
054            throw new RuntimeException("Can not create object for class:\"" + target.getName() + "\", cause:" + e.getMessage(), e);
055        }
056    }
057
058
059}
060
061
062