SpringBoot -- 获取SpringContext上下文
在开发过程中,我们可能会遇到需要动态加载某个bean的实例,或者动态获取再配置文件中配置的某个属性。此时我们就会用到SpringContext上下文。网上有许多获取SpringContext上下文的工具类,这里主要记录一下是如何获取到上下文的。
Spring Bean 的生命周期
从bean的生命周期可以看出,如果Bean实现了ApplicationContextAware接口,那么在bean准备阶段就会调用setApplicationContext()方法,并注入Spring上下文。因此,我们只需要创建一个组件,并继承ApplicationContextAware接口,此时我们在setApplicationContext()方法中就可以获取到上下文信息。
SpringContextUtils 工具类
@Component public class SpringContextUtils implements ApplicationContextAware { private static ApplicationContext applicationContext; /** * 实现setApplicationContext 将注入的 ApplicationContext 赋值给 当前类中的applicationContext * @param applicationContext * @throws BeansException */ @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } /** * 获取Spring的上下文 * @return */ public static ApplicationContext getApplicationContext(){ return applicationContext; } /** * 获取Spring上下文容器中所有Bean的名称 * @return */ public static String[] getBeanDefinitionNames(){ return applicationContext.getBeanDefinitionNames(); } /** * 根据Bean的名称获取Bean * @param name * @return */ public static Object getBean(String name){ return applicationContext.getBean(name); } /** * 根据class获取Bean * @param clazz * @param <T> * @return */ public static <T> T getBean(Class<T> clazz){ return applicationContext.getBean(clazz); } /** * 根据Bean名称获取Class * @param name * @return */ public static Class<?> getType(String name){ return applicationContext.getType(name); } /** * 根据propertyName获取配置信息 * @param propertyName * @return */ public static Object getProperty(String propertyName){ ConfigurableEnvironment env = (ConfigurableEnvironment) applicationContext.getEnvironment(); return env.getProperty(propertyName); } /** * 根据property前缀获取配置列表 * @param propertyPrefix * @return */ public static List<String> getPropertyList(String propertyPrefix){ AtomicReference<List<String>> result = new AtomicReference<>(); ConfigurableEnvironment env = (ConfigurableEnvironment) applicationContext.getEnvironment(); env.getPropertySources().stream().forEach(propertySource->{ if (propertySource instanceof OriginTrackedMapPropertySource) { List<String> props = Arrays.asList(((OriginTrackedMapPropertySource) propertySource).getPropertyNames()); result.set(props.stream().filter(e -> e.startsWith(propertyPrefix)).collect(Collectors.toList())); } }); return result.get(); } /** * 判断某个配置是否存在 * @param propertyName * @param notBlank 不能是空字符或null * @return */ public static boolean containProperty(String propertyName,boolean notBlank){ Object prop = applicationContext.getEnvironment().getProperty(propertyName); if(null==prop){ return false; }else if(notBlank && Strings.isBlank(prop.toString())){ return false; } return true; } }
上一篇:
IDEA上Java项目控制台中文乱码