Spring Boot获取上下文环境方法

来源:互联网 发布:文案好的淘宝店 编辑:程序博客网 时间:2024/05/22 10:33

方法一:

import org.springframework.beans.BeansException;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;import org.springframework.stereotype.Component;@Componentpublic class ApplicationContextHolder implements ApplicationContextAware{    // 上下文对象实例    private static ApplicationContext applicationContext;    @Override    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {        ApplicationContextHolder.applicationContext = applicationContext;    }    public static ApplicationContext getApplicationContext(){        return applicationContext;    }    public static <T> T getBean(Class<T> clazz){        return applicationContext.getBean(clazz);    }    @SuppressWarnings("unchecked")    public static <T> T getBean(String name){        return (T)applicationContext.getBean(name);    }    public static <T> T getBean(String name, Class<T> clazz){        return getApplicationContext().getBean(name, clazz);    }}


方法二:

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;    }    public static <T> T getBean(String name){        return (T)applicationContext.getBean(name);    }    public static <T> T getBean(Class<T> clazz){        return applicationContext.getBean(clazz);    }}
入口main函数:

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



阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 女装中裤 中裤七分裤 男士运动中裤 小女孩中裤 中裤配什么鞋子 中腰直筒裤 中腰三角裤 中腰裤 耐克男中裤 亚麻裤 七分裤 中裤 中年男士中裤 中裤 五分裤 女中裤七分裤 运动裤中裤 中裤 七分裤 单裤 百折裙 中观 大乘中观释论 南怀瑾唯识与中观 中视传媒 中视购物 中视 中视影业 中视尚影 中视艺考 中视太和 中视影视 中视影音 中视科技 中视体育 中视影城 中视眼镜 中视金桥 中视影院 中视北方 中视伟业 中视集团