手写Spring框架 IOC 和 AOP

avatar 2022年05月17日20:27:35 0 3233 views
博主分享免费Java教学视频,B站账号:Java刘哥 ,长期提供技术问题解决、项目定制:本站商品点此

代码演示视频:链接:https://pan.baidu.com/s/1QnEc9uAXDdgTsdEb6wjzHQ?pwd=44ih 

该项目是博主帮某985大学学生做的一个项目

一、功能介绍

实现了 IOC 和 AOP 功能,xml 配置和 注解扫描两种

xml 标签如 

beans

bean id class scope(single/prototype) autowired(byType/byName) name

property value ref name

constructor-arg 子标签 List Map Set ref value index type value ref

context:component-scan

等等

 

注解如

@Component @Service @Repository @Autowired @Qulififier @Value

 

二、代码结构

IOC

 

AOP

 

三、核心代码

1、BeanFactory

package com.liuyanzhao.springframework.beans.factory;

import com.liuyanzhao.springframework.beans.exception.BeansException;
import com.liuyanzhao.springframework.beans.factory.config.BeanDefinition;
import com.liuyanzhao.springframework.beans.factory.config.BeanPostProcessor;
import com.liuyanzhao.springframework.util.StringValueResolver;

import java.util.Map;

/**
 * Bean工厂类,这里为了简化设计模式,直接把常用方法放在Bean工厂接口里
 *
 * @Author: liuyanzhao
 * @Date: 2022/4/3 14:49
 * @Version 1.0
 */
public interface BeanFactory {

    /**
     * 往Bean定义池中放一个Bean定义
     *
     * @param beanName
     * @param beanDefinition
     */
    void registerBeanDefinition(String beanName, BeanDefinition beanDefinition);


    /**
     * 从Bean定义池中获取Bean定义
     *
     * @param beanName
     * @return
     * @throws BeansException
     */
    BeanDefinition getBeanDefinition(String beanName) throws BeansException;

    /**
     * 判断是否包含指定名称的BeanDefinition
     *
     * @param beanName
     * @return
     */
    boolean containsBeanDefinition(String beanName);

    /**
     * 将当前Bean注册到容器中
     * @param existingBean
     */
    void autowireBean(Object existingBean);

    /**
     * 根据bean名称和bean定义创建Bean对象
     * 如果是单例Bean放到单例Bean池中,然后返回Bean对象
     * 如果不是单例,则直接返回Bean对象
     *
     * @param beanName
     * @param beanDefinition
     * @return
     * @throws BeansException
     */
    Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args) throws BeansException;

    /**
     * 根据bean名称和bean定义创建Bean对象
     * 如果是单例Bean放到单例Bean池中,然后返回Bean对象
     * 如果不是单例,则直接返回Bean对象
     *
     * @param beanName
     * @param existingBean
     * @param beanDefinition
     * @return
     * @throws BeansException
     */
    Object createBean(String beanName, Object existingBean, BeanDefinition beanDefinition, Object[] args) throws BeansException;


    /**
     * 从Bean单例池中获取Bean对象,如果获取不到再调用上面createBean方法创建Bean对象
     *
     * @param name
     * @return
     * @throws BeansException
     */
    Object getBean(String name) throws BeansException;

    /**
     * 同上,只是能根据泛型获取Bean对象,无需强制类型转换
     * *
     *
     * @param name
     * @param requiredType
     * @param <T>
     * @return
     * @throws BeansException
     */
    <T> T getBean(String name, Class<T> requiredType) throws BeansException;

    /**
     * 同上
     *
     * @param requiredType
     * @param <T>
     * @return
     * @throws BeansException
     */
    <T> T getBean(Class<T> requiredType) throws BeansException;


    /**
     * 也是获取Bean对象,只不过传入了一些成员变量的参数
     *
     * @param name
     * @param args
     * @return
     * @throws BeansException
     */
    Object getBean(String name, Object... args) throws BeansException;

    /**
     * 返回注册表中所有的Bean名称
     *
     * @return
     */
    String[] getBeanDefinitionNames();


    /**
     * 获得Bean定义集合
     * @return
     */
    Map<String, BeanDefinition> getBeanDefinitionMap();


    /**
     * 添加属性值
     *
     * @param valueResolver
     */
    void addEmbeddedValueResolver(StringValueResolver valueResolver);


    /**
     * 获得属性值
     *
     * @param value
     * @return
     */
    String resolveEmbeddedValue(String value);

    /**
     * 按照类型返回 Bean 实例
     * @param type
     * @param <T>
     * @return
     * @throws BeansException
     */
    <T> Map<String, T> getBeansOfType(Class<T> type) throws BeansException;


    /**
     * 注册Bean后置处理器
     * @param beanPostProcessor
     */
    void addBeanPostProcessor(BeanPostProcessor beanPostProcessor);

    /**
     * 销毁工厂
     * @throws Exception
     */
    void close() ;
}

 

2、ApplicationContext

package com.liuyanzhao.springframework.context;

import com.liuyanzhao.springframework.beans.exception.BeansException;
import com.liuyanzhao.springframework.beans.factory.BeanFactory;

/**
 * 应用上下文
 * @Author: liuyanzhao
 * @Date: 2022/4/4 11:11
 * @Version 1.0
 */
public interface ApplicationContext {

    /**
     * 刷新容器
     * 即初始化操作
     *
     * @throws BeansException
     */
    void refresh() ;

    /**
     * 从Bean单例池中获取Bean对象
     *
     * @param name
     * @return
     * @throws BeansException
     */
    Object getBean(String name) throws BeansException;

    /**
     * 同上,只是能根据泛型获取Bean对象,无需强制类型转换
     * *
     *
     * @param name
     * @param requiredType
     * @param <T>
     * @return
     * @throws BeansException
     */
    <T> T getBean(String name, Class<T> requiredType) throws BeansException;

    /**
     * 同上
     *
     * @param requiredType
     * @param <T>
     * @return
     * @throws BeansException
     */
    <T> T getBean(Class<T> requiredType) throws BeansException;


    /**
     * 也是获取Bean对象,只不过传入了一些成员变量的参数
     *
     * @param name
     * @param args
     * @return
     * @throws BeansException
     */
    Object getBean(String name, Object... args) throws BeansException;

    /**
     * 获得工厂对象
     * @return
     */
    BeanFactory getBeanFactory();


    /**
     * 销毁工厂
     * @throws Exception
     */
    void close() ;
}

 

3、ClassPathXmlApplicationContext

package com.liuyanzhao.springframework.context;

import com.liuyanzhao.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import com.liuyanzhao.springframework.beans.exception.BeansException;
import com.liuyanzhao.springframework.beans.factory.BeanFactory;
import com.liuyanzhao.springframework.beans.factory.PropertyPlaceholderConfigurer;
import com.liuyanzhao.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor;
import com.liuyanzhao.springframework.beans.factory.config.BeanDefinition;
import com.liuyanzhao.springframework.beans.factory.support.BeanDefinitionReader;
import com.liuyanzhao.springframework.beans.factory.support.DefaultBeanFactory;
import com.liuyanzhao.springframework.beans.factory.xml.XmlBeanDefinitionReader;

import java.util.Map;

/**
 * classpath下读取XML文件的上下文实现
 *
 * @Author: liuyanzhao
 * @Date: 2022/4/4 11:14
 * @Version 1.0
 */
public class ClassPathXmlApplicationContext implements ApplicationContext {

    /**
     * 配置文件位置,暂时只考虑一个配置文件的情况
     */
    private String[] configLocation;

    /**
     * Bean工厂
     */
    private BeanFactory beanFactory;

    public ClassPathXmlApplicationContext(String configLocation) {
        this.configLocation = new String[]{configLocation};
        // 直接调用初始化
        this.refresh();
    }

    public ClassPathXmlApplicationContext(String[] configLocation) {
        this.configLocation = configLocation;
        // 直接调用初始化
        this.refresh();
    }

    @Override
    public void refresh()  {
        try {
            // 1.创建BeanFactory 工厂
            beanFactory = new DefaultBeanFactory();
            // 2.加载Bean定义
            BeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
            beanDefinitionReader.loadBeanDefinitions(this.configLocation);

            // 3. Bean工厂后置处理器,即对Bean工厂做一些后置的处理
            // 获取配置文件里的属性值,如获取jdbc.proerties里的jdbc.name的值
            PropertyPlaceholderConfigurer placeholderConfigurer = (PropertyPlaceholderConfigurer) beanFactory.getBean("propertyPlaceholderConfigurer");
            if (placeholderConfigurer != null) {
                placeholderConfigurer.postProcessBeanFactory(beanFactory);
            }

            // 4.注册Bean工厂
            beanFactory.registerBeanDefinition("autowiredAnnotationBeanPostProcessor", new BeanDefinition(AutowiredAnnotationBeanPostProcessor.class));
            beanFactory.registerBeanDefinition("defaultAdvisorAutoProxyCreator", new BeanDefinition(DefaultAdvisorAutoProxyCreator.class));
            beanFactory.addBeanPostProcessor(beanFactory.getBean(AutowiredAnnotationBeanPostProcessor.class));
            beanFactory.addBeanPostProcessor(beanFactory.getBean(DefaultAdvisorAutoProxyCreator.class));

            // 5.提前实例化单例Bean(可选)
            Map<String, BeanDefinition> beanDefinitionMap = beanFactory.getBeanDefinitionMap();
//            for (String beanName : beanDefinitionMap.keySet()) {
//                Object bean = beanFactory.getBean(beanName);
//                System.out.println(bean);
//            }

            // 6.创建成功
            System.out.println("My-Spring容器初始化完成");
            System.out.println("共扫描到了 " + beanDefinitionMap.size() + " 个Bean定义,如下(Bean名称 --> Class)");
            System.out.println("--------------------------------------------------------------------------------------------------------------------------------------");
            for (Map.Entry<String, BeanDefinition> entry : beanDefinitionMap.entrySet()) {
                System.out.println(entry.getKey() + "  -->  " + entry.getValue().getBeanClass().getName());
            }
            System.out.println("--------------------------------------------------------------------------------------------------------------------------------------\n");
        } catch (Exception e) {
            e.printStackTrace();
            // 发生异常时,关闭上下文
            this.close();
            System.exit(0);
        }
    }

    @Override
    public Object getBean(String name) throws BeansException {
        return beanFactory.getBean(name);
    }

    @Override
    public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
        return beanFactory.getBean(name, requiredType);
    }

    @Override
    public <T> T getBean(Class<T> requiredType) throws BeansException {
        return beanFactory.getBean(requiredType);
    }

    @Override
    public Object getBean(String name, Object... args) throws BeansException {
        return beanFactory.getBean(name, args);
    }

    @Override
    public BeanFactory getBeanFactory() {
        return beanFactory;
    }

    @Override
    public void close() {
        System.out.println("开始关闭上下文");
        beanFactory.close();
        System.out.println("关闭上下文结束");

    }
}

 

4、DefaultBeanFactory

package com.liuyanzhao.springframework.beans.factory.support;

import cn.hutool.core.bean.BeanUtil;
import com.liuyanzhao.springframework.beans.exception.BeansException;
import com.example.springframework.beans.factory.*;
import com.liuyanzhao.springframework.beans.factory.config.BeanDefinition;
import com.liuyanzhao.springframework.beans.factory.config.BeanPostProcessor;
import com.liuyanzhao.springframework.beans.factory.config.BeanReference;
import com.liuyanzhao.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor;
import com.liuyanzhao.springframework.util.StringValueResolver;
import com.liuyanzhao.springframework.beans.factory.*;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

/**
 * bean工厂默认实现类
 * 继承单例Bean注册器类
 *
 * @Author: liuyanzhao
 * @Date: 2022/4/3 15:42
 * @Version 1.0
 */
public class DefaultBeanFactory extends DefaultSingletonBeanRegistry implements BeanFactory {

    /**
     * 定义一个Bean定义池子,维护Bean名称和Bean定义的关系(即名称和类类型的关系)
     */
    public Map<String, BeanDefinition> beanDefinitionMap = new HashMap<>();

    /**
     * @Value的属性值集合
     */
    public List<StringValueResolver> embeddedValueResolvers = new ArrayList<>();

    /**
     * BeanPostProcessors to apply in createBean
     */
    public List<BeanPostProcessor> beanPostProcessors = new ArrayList<BeanPostProcessor>();

    @Override
    public Object getBean(String name) throws BeansException {
        return doGetBean(name, null);
    }

    @Override
    public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
        return (T) this.getBean(name);
    }

    @Override
    public Object getBean(String name, Object... args) throws BeansException {
        return doGetBean(name, args);
    }

    @Override
    public <T> T getBean(Class<T> requiredType) throws BeansException {
        List<String> beanNames = new ArrayList<>();
        for (Map.Entry<String, BeanDefinition> entry : beanDefinitionMap.entrySet()) {
            Class beanClass = entry.getValue().getBeanClass();
            // 判断是否为子类或者接口实现的类
            // 如 Dog 是 Animal 的子类,为true;CCServiceImpl是CCService的接口实现,也为true
            if (requiredType.isAssignableFrom(beanClass)) {
                beanNames.add(entry.getKey());
            }
        }
        if (1 == beanNames.size()) {
            return getBean(beanNames.get(0), requiredType);
        }

        return null;
    }

    /**
     * 获取Bean
     *
     * @param name
     * @param args
     * @param <T>
     * @return
     */
    private <T> T doGetBean(final String name, final Object[] args) {
        // 先从单例池里拿,拿不到再创建
        Object bean = getSingleton(name);
        if (bean != null) {
            return (T) bean;
        }

        BeanDefinition beanDefinition = getBeanDefinition(name);
        if (beanDefinition == null) {
            return null;
        }
        return (T) createBean(name, beanDefinition, args);
    }

    @Override
    public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) {
        beanDefinitionMap.put(beanName, beanDefinition);
    }

    @Override
    public BeanDefinition getBeanDefinition(String beanName) throws BeansException {
        return beanDefinitionMap.get(beanName);
    }

    @Override
    public boolean containsBeanDefinition(String beanName) {
        return beanDefinitionMap.containsKey(beanName);
    }

    @Override
    public void autowireBean(Object existingBean) {
        String className = existingBean.getClass().getName();
        BeanDefinition beanDefinition = new BeanDefinition(existingBean.getClass());
        beanDefinitionMap.put(className, beanDefinition);
        this.createBean(className, existingBean, beanDefinition, new Object[]{});
    }

    @Override
    public Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args) throws BeansException {
        return this.createBean(beanName, null, beanDefinition, args);
    }

    @Override
    public Object createBean(String beanName, Object existingBean, BeanDefinition beanDefinition, Object[] args) throws BeansException {
        Object bean;
        try {
            // 判断是否返回代理 Bean 对象
            bean = resolveBeforeInstantiation(beanName, beanDefinition);
            if (null != bean) {
                return bean;
            }

            // 实例化 Bean,如果已经提供了对象,直接使用
            bean = existingBean != null ? existingBean : this.createBeanInstance(beanDefinition, args);

            // 处理循环依赖,将实例化后的Bean对象提前放入缓存中暴露出来
            if (BeanDefinition.SCORE_SINGLETON.equals(beanDefinition.getScope())) {
                Object finalBean = bean;
                addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, beanDefinition, finalBean));
            }

            // 实例化后判断
            boolean continueWithPropertyPopulation = applyBeanPostProcessorsAfterInstantiation(beanName, bean);
            if (!continueWithPropertyPopulation) {
                return bean;
            }

            // 在设置 Bean 属性之前,允许 BeanPostProcessor 修改属性值
            applyBeanPostProcessorsBeforeApplyingPropertyValues(beanName, bean, beanDefinition);

            // 给 Bean 填充属性
            applyPropertyValues(beanName, bean, beanDefinition);

            // 执行 Bean 的初始化方法和 BeanPostProcessor 的前置和后置处理方法
            bean = initializeBean(beanName, bean, beanDefinition);

        } catch (Exception e) {
            e.printStackTrace();
            throw new BeansException("Bean属性设置失败", e);
        }
        // 如果要求作用域为单例,则放到单例池中
        if (BeanDefinition.SCORE_SINGLETON.equals(beanDefinition.getScope())) {
            addSingleton(beanName, bean);
        }
        return bean;
    }


    protected Object getEarlyBeanReference(String beanName, BeanDefinition beanDefinition, Object bean) {
        Object exposedObject = bean;
        for (BeanPostProcessor beanPostProcessor : getBeanPostProcessors()) {
            exposedObject = beanPostProcessor.getEarlyBeanReference(exposedObject, beanName);
            if (null == exposedObject) {
                return exposedObject;
            }
        }
        return exposedObject;
    }

    /**
     * 执行 Bean 的初始化方法和 BeanPostProcessor 的前置和后置处理方法
     *
     * @param beanName
     * @param bean
     * @param beanDefinition
     * @return
     */
    private Object initializeBean(String beanName, Object bean, BeanDefinition beanDefinition) {


        // 给 BeanPostProcessor 设置 BeanFactory
        if (bean instanceof BeanPostProcessor) {
            ((BeanPostProcessor) bean).setBeanFactory(this);
        }

        // 2. 执行 BeanPostProcessor Before 处理
        Object wrappedBean = applyBeanPostProcessorsBeforeInitialization(bean, beanName);

        // 3. 执行 BeanPostProcessor After 处理
        wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
        return wrappedBean;
    }


    /**
     * 在设置 Bean 属性之前,允许 BeanPostProcessor 修改属性值
     *
     * @param beanName
     * @param bean
     * @param beanDefinition
     */
    protected void applyBeanPostProcessorsBeforeApplyingPropertyValues(String beanName, Object bean, BeanDefinition beanDefinition) {
        for (BeanPostProcessor beanPostProcessor : getBeanPostProcessors()) {
            PropertyValues pvs = beanPostProcessor.postProcessPropertyValues(beanDefinition.getPropertyValues(), bean, beanName);
            if (null != pvs) {
                for (PropertyValue propertyValue : pvs.getPropertyValues()) {
                    beanDefinition.getPropertyValues().addPropertyValue(propertyValue);
                }
            }

        }
    }

    /**
     * // 判断是否返回代理 Bean 对象
     *
     * @param beanName
     * @param beanDefinition
     * @return
     */
    private Object resolveBeforeInstantiation(String beanName, BeanDefinition beanDefinition) {
        Object bean = applyBeanPostProcessorsBeforeInstantiation(beanDefinition.getBeanClass(), beanName);
        if (null != bean) {
            bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
        }
        return bean;
    }

    /**
     * 在 Bean 对象执行实例化方法之前,执行此方法
     *
     * @param beanClass
     * @param beanName
     * @return
     */
    private Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {
        for (BeanPostProcessor beanPostProcessor : getBeanPostProcessors()) {
            Object result = beanPostProcessor.postProcessBeforeInstantiation(beanClass, beanName);
            if (null != result) {
                return result;
            }

        }
        return null;
    }


    /**
     * 在 Bean 对象执行实例化方法之后,执行此方法
     * Bean 实例化后对于返回 false 的对象,不在执行后续设置 Bean 对象属性的操作
     *
     * @param beanName
     * @param bean
     * @return
     */
    private boolean applyBeanPostProcessorsAfterInstantiation(String beanName, Object bean) {
        boolean continueWithPropertyPopulation = true;
        for (BeanPostProcessor beanPostProcessor : getBeanPostProcessors()) {
            if (beanPostProcessor instanceof AutowiredAnnotationBeanPostProcessor) {
                if (!beanPostProcessor.postProcessAfterInstantiation(bean, beanName)) {
                    continueWithPropertyPopulation = false;
                    break;
                }
            }
        }
        return continueWithPropertyPopulation;
    }


    /**
     * 在 Bean 对象执行初始化方法之前,执行此方法
     *
     * @param existingBean
     * @param beanName
     * @return
     * @throws BeansException
     */
    public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) throws BeansException {
        Object result = existingBean;
        for (BeanPostProcessor processor : getBeanPostProcessors()) {
            Object current = processor.postProcessBeforeInitialization(result, beanName);
            if (null == current) return result;
            result = current;
        }
        return result;
    }

    /**
     * 在 Bean 对象执行初始化方法之后,执行此方法
     *
     * @param existingBean
     * @param beanName
     * @return
     * @throws BeansException
     */
    private Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException {
        Object result = existingBean;
        for (BeanPostProcessor processor : getBeanPostProcessors()) {
            Object current = processor.postProcessAfterInitialization(result, beanName);
            if (null == current) {
                return result;
            }
            result = current;
        }
        return result;
    }


    @Override
    public String[] getBeanDefinitionNames() {
        return beanDefinitionMap.keySet().toArray(new String[0]);
    }

    @Override
    public Map<String, BeanDefinition> getBeanDefinitionMap() {
        return beanDefinitionMap;
    }

    @Override
    public void addEmbeddedValueResolver(StringValueResolver valueResolver) {
        this.embeddedValueResolvers.add(valueResolver);
    }

    @Override
    public String resolveEmbeddedValue(String value) {
        String result = value;
        for (StringValueResolver resolver : this.embeddedValueResolvers) {
            result = resolver.resolveStringValue(result);
        }
        return result;
    }

    @Override
    public <T> Map<String, T> getBeansOfType(Class<T> type) throws BeansException {
        Map<String, T> result = new HashMap<>();
        beanDefinitionMap.forEach((beanName, beanDefinition) -> {
            Class beanClass = beanDefinition.getBeanClass();
            if (type.isAssignableFrom(beanClass)) {
                result.put(beanName, (T) getBean(beanName));
            }
        });
        return result;
    }

    @Override
    public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
        this.beanPostProcessors.remove(beanPostProcessor);
        this.beanPostProcessors.add(beanPostProcessor);
    }

    @Override
    public void close() {
        System.out.println("开始关闭Bean工厂");
        // 清空单例池
        Map<String, Object> singletonObjects = getSingletonObjects();
        for (Map.Entry<String, Object> entry : singletonObjects.entrySet()) {
            Object value = entry.getValue();
            String key = entry.getKey();
            value = null;
            singletonObjects.remove(key);
        }
        System.out.println("关闭Bean工厂结束");
    }

    /**
     * Bean 属性填充
     */
    protected void applyPropertyValues(String beanName, Object bean, BeanDefinition beanDefinition) {
        try {
            PropertyValues propertyValues = beanDefinition.getPropertyValues();
            for (PropertyValue propertyValue : propertyValues.getPropertyValues()) {

                String name = propertyValue.getName();
                Object value = propertyValue.getValue();

                if (value instanceof BeanReference) {

                    // A 依赖 B,获取 B 的实例化
                    // 判断注入类型是 byType 还是 byName
                    BeanReference beanReference = (BeanReference) value;
                    if (BeanDefinition.AUTOWIRED_BY_NAME.equals(beanDefinition.getAutowired())) {
                        // 根据 name 获取Bean
                        value = getBean(beanReference.getBeanName());
                    } else if (BeanDefinition.AUTOWIRED_BY_TYPE.equals(beanDefinition.getAutowired())) {
                        // 根据 类类型即class 获取Bean
                        value = getBean(beanReference.getBeanClass());
                    } else {
                        // 先根据 name 获取,获取不到再根据 class 获取
                        value = getBean(beanReference.getBeanName(), beanReference.getBeanClass());
                    }

                    value = getBean(beanReference.getBeanName());

                }
                // 属性填充
                BeanUtil.setFieldValue(bean, name, value);
            }
        } catch (Exception e) {
            throw new BeansException("Error setting property values:" + beanName);
        }
    }

    /**
     * 创建Bean对象
     *
     * @param beanDefinition
     * @param args
     * @return
     */
    private Object createBeanInstance(BeanDefinition beanDefinition, Object[] args) {
        ConstructorArgValue[] constructorValues = {};
        ConstructorArgValues constructorArgValues = beanDefinition.getConstructorArgValues();
        if (constructorArgValues != null) {
            constructorValues = beanDefinition.getConstructorArgValues().getConstructorValues();
        }
        if (constructorValues != null && constructorValues.length > 0) {
            args = new Object[constructorValues.length];
        }
        Constructor constructorToUse = null;
        Class<?> beanClass = beanDefinition.getBeanClass();
        Constructor<?>[] declaredConstructors = beanClass.getDeclaredConstructors();
        for (Constructor ctor : declaredConstructors) {
            if (null != args && ctor.getParameterTypes().length == args.length) {
                constructorToUse = ctor;
                // 处理下 args
                this.handlerConstructorArgValues(ctor, constructorArgValues, args);
                break;
            }
        }

        Class clazz = beanDefinition.getBeanClass();
        try {
            if (null != constructorToUse) {
                // 调用有参构造器,传参数
                return clazz.getDeclaredConstructor(constructorToUse.getParameterTypes()).newInstance(args);
            } else {
                // 调用无参构造器
                return clazz.getDeclaredConstructor().newInstance();
            }
        } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
            throw new BeansException("创建Bean失败 [" + clazz.getName() + "]", e);
        }

    }

    /**
     * 处理构造器参数
     *
     * @param ctor
     * @param constructorArgValues
     * @param args
     */
    private void handlerConstructorArgValues(Constructor ctor, ConstructorArgValues constructorArgValues, Object[] args) {
        ConstructorArgValue[] constructorValues = constructorArgValues.getConstructorValues();
        int i = 0;
        for (Class parameterType : ctor.getParameterTypes()) {
            // 先根据构造方法参数里的index找参数
            ConstructorArgValue constructorValue = constructorArgValues.getConstructorValueByIndex(String.valueOf(i));
            if (constructorValue == null) {
                // 找不到,直接当前这个参数
                constructorValue = constructorValues[i];

            }
            // 目前只支持String类型、常见基本类型
            if (parameterType == String.class) {
                args[i] = constructorValue.getValue();
            } else if (parameterType == Byte.class) {
                args[i] = Byte.valueOf(constructorValue.getValue());
            } else if (parameterType == Short.class) {
                args[i] = Short.valueOf(constructorValue.getValue());
            } else if (parameterType == Integer.class) {
                args[i] = Integer.valueOf(constructorValue.getValue());
            } else if (parameterType == Long.class) {
                args[i] = Long.valueOf(constructorValue.getValue());
            } else if (parameterType == Double.class) {
                args[i] = Double.valueOf(constructorValue.getValue());
            } else if (parameterType == Float.class) {
                args[i] = Float.valueOf(constructorValue.getValue());
            } else if (parameterType == Boolean.class) {
                args[i] = Boolean.valueOf(constructorValue.getValue());
            }
            i++;
        }
    }

    public List<StringValueResolver> getEmbeddedValueResolvers() {
        return embeddedValueResolvers;
    }

    public List<BeanPostProcessor> getBeanPostProcessors() {
        return beanPostProcessors;
    }
}

 

等等

需要完整代码可以联系博主

 

 

 

  • 微信
  • 交流学习,资料分享
  • weinxin
  • 个人淘宝
  • 店铺名:言曌博客咨询部

  • (部分商品未及时上架淘宝)
avatar

发表评论

avatar 登录者:匿名
匿名评论,评论回复后会有邮件通知

  

已通过评论:0   待审核评论数:0