package com.ssyf.common.web.holder;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 对象句柄
 * @author huwei
 * @date 2023/2/12 21:15
 */
public class Holder {

    private static ApplicationContext applicationContext;

    static void init(ApplicationContext context){
        applicationContext = context;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 获取指定类的bean
     * @param cls
     * @param <T>
     * @return
     */
    public static <T> List<T> getBeans(Class<T> cls){
        return applicationContext.getBeansOfType(cls)
                .entrySet()
                .stream()
                .collect(ArrayList::new ,(l , r)->{
                    l.add(r.getValue());
                },(l ,r)->{});
    }

    @Component
    public static class Init{
        public Init(@Autowired ApplicationContext applicationContext){
            Holder.init(applicationContext);
        }
    }
}
