package com.yeejoin.amos.api.common.restful.utils;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 手动注入bean
 * @author andrew
 *
 */
@Component
public class ApplicationContextUtils implements ApplicationContextAware {
    @Autowired
    private static ApplicationContext context;

    //方式一:传Class对象
    //新建对象实例并注入其他springbean
    public static <T> T newAutoWiredInstance(Class<T> beanClass){
        return (T)context.getAutowireCapableBeanFactory()
                .autowire(beanClass, AutowireCapableBeanFactory.AUTOWIRE_AUTODETECT, true);
    }

    //方式二:传bean对象
    //已经new出来的对象进行注入
    public static <T> T autowire(T bean){
        context.getAutowireCapableBeanFactory()
                .autowireBeanProperties(bean, AutowireCapableBeanFactory.AUTOWIRE_AUTODETECT, true);
        return bean;
    }

    /**
     * 插入ApplicationContext
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }
    /**
     * 获取ApplicationContext
     */
    public static ApplicationContext getApplicationContext() {
        return context;
    }


    /**
     * 通过name获取 Bean
     */
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }


    /**
     * 通过class获取Bean.
     */
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    /**
     *通过name,以及Clazz返回指定的Bean
     */
    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }

}

