首页 > 编程 > Java > 正文

springboot 使用上下文获取bean

2019-11-26 08:46:20
字体:
来源:转载
供稿:网友

问题

在使用springboot开发项目过程中,有些时候可能出现说会有在spring容器加载前就需要注入bean的类,这个时候如果直接使用@Autowire注解,则会出现控制针异常!

解决办法

如下:

创建一个springContextUtil类

package cn.eangaie.appcloud.util;import org.springframework.context.ApplicationContext;public class SpringContextUtil {  private static ApplicationContext applicationContext;  //获取上下文  public static ApplicationContext getApplicationContext() {    return applicationContext;  }  //设置上下文  public static void setApplicationContext(ApplicationContext applicationContext) {    SpringContextUtil.applicationContext = applicationContext;  }  //通过名字获取上下文中的bean  public static Object getBean(String name){    return applicationContext.getBean(name);  }  //通过类型获取上下文中的bean  public static Object getBean(Class<?> requiredType){    return applicationContext.getBean(requiredType);  }}


在AppcloudApplication.class 启动类里边,将初始化该类,并将context注入进去

public class AppcloudApplication {  public static void main(String[] args) {    ApplicationContext context=SpringApplication.run(AppcloudApplication.class, args);    SpringContextUtil.setApplicationContext(context);  }}

在需要注入bean的地方,使用getBean(bean名称)的方式获取

MessageTemplateController messageTemplateController= (MessageTemplateController) SpringContextUtil.getBean("messageTemplateController");

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表