All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.zys.mybatis.utils.SpringUtil Maven / Gradle / Ivy

package com.zys.mybatis.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;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author zys
 * @date 2020\4\29 0029
 */
@Component
public class SpringUtil implements ApplicationContextAware {


	private static ApplicationContext applicationContext;

	private static final Map, Integer> pollMap = new ConcurrentHashMap<>();


	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		SpringUtil.applicationContext = applicationContext;
	}

	/**
	 * 获取bean
	 * @param classes bean类型
	 * @return bean对象
	 */
	public static  T getBean (Class classes) {
		return applicationContext.getBean(classes);
	}

	/**
	 * 同类型多个bean,获取第一个
	 * @param classes class
	 * @return bean对象
	 */
	public static  T getFirstBean(Class classes) {
		String[] beanNamesForType = applicationContext.getBeanNamesForType(classes);
		return applicationContext.getBean(beanNamesForType[0], classes);
	}

	/**
	 * 同类型多个bean,轮回获取bean
	 * @param classes class
	 * @return bean对象
	 */
	public static  T getPollBean(Class classes) {
		int index = pollMap.computeIfAbsent(classes, k -> 0);
		String[] beanNamesForType = applicationContext.getBeanNamesForType(classes);
		if (index == beanNamesForType.length) {
			pollMap.put(classes, 0);
			index = 0;
		}
		String beanName = beanNamesForType[index];
		pollMap.put(classes, ++index);
		return applicationContext.getBean(beanName, classes);
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy