package com.dsh.utils;
|
|
import org.springframework.beans.BeansException;
|
import org.springframework.context.ApplicationContext;
|
import org.springframework.context.ApplicationContextAware;
|
import org.springframework.stereotype.Component;
|
import org.springframework.util.Assert;
|
|
/**
|
* * @author: lihong .
|
* * @email: 765907456@qq.com .
|
* * @createTime: 19-7-15 上午11:14 .
|
* * description: api方式获取bean.
|
**/
|
@Component
|
public class SpringBeanUtils implements ApplicationContextAware {
|
private static ApplicationContext APPLICATION_CONTEXT;
|
|
/**
|
* 根据名称获取Bean
|
*
|
* @param beanName
|
* @return
|
*/
|
public static <T> T getBean(String beanName) {
|
Assert.hasText(beanName, "获取bean名称不能为空.");
|
if (APPLICATION_CONTEXT.containsBean(beanName)) {
|
return (T) APPLICATION_CONTEXT.getBean(beanName);
|
}
|
return null;
|
}
|
|
/**
|
* 根据类型获取bean
|
*
|
* @param targetType
|
* @param <T>
|
* @return
|
*/
|
public static <T> T getBean(Class<T> targetType) {
|
Assert.notNull(targetType, "目标类型不能为空.");
|
return APPLICATION_CONTEXT.getBean(targetType);
|
}
|
|
/**
|
* 根据类型名称获取bean
|
*
|
* @param beanName
|
* @param targetType
|
* @param <T>
|
* @return
|
*/
|
public static <T> T getBean(String beanName, Class<T> targetType) {
|
Assert.notNull(targetType, "目标类型不能为空");
|
Assert.hasText(beanName, "bean名称不能为空.");
|
if (APPLICATION_CONTEXT.containsBean(beanName)) {
|
return APPLICATION_CONTEXT.getBean(beanName, targetType);
|
}
|
return null;
|
|
}
|
|
|
@Override
|
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
|
SpringBeanUtils.APPLICATION_CONTEXT = applicationContext;
|
}
|
}
|