美文网首页
Spring Boot 获取上下文

Spring Boot 获取上下文

作者: Frankeen | 来源:发表于2019-08-23 11:04 被阅读0次
    新建获取上下文工具类SpringContextUtil
    package com.frank.lmsg.base.utils;
    
    import org.springframework.context.ApplicationContext;
    
    /**
     * Description: 获取上下文工具类
     * Auth: Frank
     * Date: 2019-08-23
     * Time: 上午 10:44
     */
    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);
        }
    
    
    }
    
    
    在Application里面初始化上下文
    package com.frank.lmsg;
    
    import com.frank.lmsg.base.utils.SpringContextUtil;
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.ApplicationContext;
    
    @SpringBootApplication
    @MapperScan("com.frank.lmsg.mybatis.mapper")
    public class LmsgApplication {
    
        public static void main(String[] args) {
            ApplicationContext app = SpringApplication.run(LmsgApplication.class, args);
            SpringContextUtil.setApplicationContext(app);
        }
    
    }
    
    
    获取上下文
        ApplicationContext app = SpringContextUtil.getApplicationContext();
    

    相关文章

      网友评论

          本文标题:Spring Boot 获取上下文

          本文链接:https://www.haomeiwen.com/subject/ppjzsctx.html