SpringBoot中SpringContextHolder工具类使用
SpringContextHolder作用:以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候取出ApplicaitonContext。SpringContextHolder@Componentpublic class SpringContextHolder implements ApplicationContextAware {/*** 以静态变量保
·
SpringContextHolder作用:
以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候取出ApplicaitonContext。
SpringContextHolder
@Component
public class SpringContextHolder implements ApplicationContextAware {
/**
* 以静态变量保存ApplicationContext,可在任意代码中取出ApplicaitonContext.
*/
private static ApplicationContext context;
/**
* 实现ApplicationContextAware接口的context注入函数, 将其存入静态变量.
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextHolder.context = applicationContext;
}
/**
* 获取applicationContext
* @return
*/
public ApplicationContext getApplicationContext() {
return context;
}
/**
* 通过name获取 Bean.
* @param name
* @return
*/
public static Object getBean(String name){
return context.getBean(name);
}
/**
* 通过class获取Bean.
* @param clazz
* @param <T>
* @return
*/
public static <T> Map<String, T> getBeans(Class<T> clazz){
return context.getBeansOfType(clazz);
}
/**
* 通过class获取Bean.
* @param clazz
* @param <T>
* @return
*/
public static <T> T getBean(Class<T> clazz){
return context.getBean(clazz);
}
/**
* 通过name,以及Clazz返回指定的Bean
* @param name
* @param clazz
* @param <T>
* @return
*/
public static <T> T getBean(String name, Class<T> clazz){
return context.getBean(name, clazz);
}
}
使用
protected TaskPushModeContext taskPushModeContext;
@Override
public void init(Task task) {
taskPushModeContext = (TaskPushModeContext) SpringContextHolder.getBean("taskPushModeContext");
}
TaskPushModeContext
@Slf4j
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Component
public class TaskPushModeContext {
private ITaskPushMode pushTaskMode;
@Autowired
private CmsEnvironmentConfig cmsEnvironmentConfig;
}
参考文章
https://blog.csdn.net/weixin_30892037/article/details/96457618
https://blog.csdn.net/weixin_46082526/article/details/108759113
https://blog.csdn.net/Jamel_LiToo/article/details/86443766
更多推荐
已为社区贡献13条内容
所有评论(0)