java注入工具类

package cn.xd.dcol.railway.business.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
 * @Author Caocs
 * @Date 2023/2/16
 */
@Component
public class ApplicationContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext = null;

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        if (applicationContext == null) {
            applicationContext = context;
        }
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static  Map getBeans(Class clazz) {
        return applicationContext.getBeansOfType(clazz);
    }

    public static  T getBean(Class clazz) {
        return applicationContext.getBean(clazz);
    }
}




调用方法

 //注入bean
        ITrainOverLoadService iTrainOverLoadService = ApplicationContextUtil.getBean(ITrainOverLoadService.class);

你可能感兴趣的:(java,开发语言)