springboot use context to obtain bean

springboot- use context to obtain bean

In use springboot development process, some time may have said before spring loaded containers will need to inject the bean class appears, at this time if the direct use @Autowire comment will appear abnormal control needle!

Solution is as follows:

  • Creating a class 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);
    }
}
  • In AppcloudApplication.class inside startup class, the class will be initialized, and injected into context
public class AppcloudApplication {

    public static void main(String[] args) {
        ApplicationContext context=SpringApplication.run(AppcloudApplication.class, args);
        SpringContextUtil.setApplicationContext(context);
    }
}
  • Where needed injection of the bean, use getBean (bean name) way to get
MessageTemplateController messageTemplateController= (MessageTemplateController) SpringContextUtil.getBean("messageTemplateController");

Reference blog: SpringBoot-- filter bean problem of injecting null pointer

Guess you like

Origin www.cnblogs.com/w53064/p/11040206.html