Springboot获取bean的工具类
在Spring boot中,我们有时候需要在工具类中获取Spring bean,工具类中的方法都是静态的,并且为了可以直接通过类名.方法名()的方式调用方法,也不会把Spring bean注入到工具类中,此时可以写一个获取bean的工具类,通过静态方法获取bean,代码如下:
/*** Bean工具类*/
@Configuration
public class BeanUtil implements ApplicationContextAware {private static ApplicationContext applicationContext;@Overridepublic void setApplicationContext(ApplicationContext context) throws BeansException {applicationContext = context;}/*** 通过类型获取bean** @param beanClass bean的class类型* @param <T> 泛型* @return bean*/public static <T> T getBean(Class<T> beanClass) {return applicationContext.getBean(beanClass);}/*** 通过名称获取bean** @param beanName bean的名称* @param <T> 泛型* @return bean*/public static <T> T getBean(String beanName) {return (T) applicationContext.getBean(beanName);}
}
在代码中,我们可以通过如下方式获取到bean(假如Spring容器中有一个UserService bean)
// 通过类型获取bean
BeanUtil.getBean(UserService.class);
// 通过名称获取bean
BeanUtil.getBean("userService");