美文网首页工具类
SpringContextUtils

SpringContextUtils

作者: fanderboy | 来源:发表于2021-12-27 23:38 被阅读0次

'''

/**

* @ClassName: SpringContextUtils

* @Description:

* @Author: wugongzi

* @Date: 2021/12/27 16:53

* @Version: 1.0

*/

@Slf4j

@Component

public class SpringContextUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

        if (SpringContextUtils.applicationContext == null) {

            SpringContextUtils.applicationContext = applicationContext;

        }

        log.info("========ApplicationContext配置成功,在普通类可以通过调用SpringUtils.getAppContext()获取applicationContext对象,applicationContext=" + SpringContextUtils.applicationContext + "========");

    }

    /**

    * 获取applicationContext

    *

    * @return

    */

    public static ApplicationContext getApplicationContext() {

        return applicationContext;

    }

    /**

    * 通过name获取 Bean.

    *

    * @param name

    * @return

    */

    public static Object getBean(String name) {

        return getApplicationContext().getBean(name);

    }

    /**

    * 通过class获取Bean.

    *

    * @param clazz

    * @param <T>

    * @return

    */

    public static <T> T getBean(Class<T> clazz) {

        return getApplicationContext().getBean(clazz);

    }

    /**

    * 通过name,以及Clazz返回指定的Bean

    *

    * @param name

    * @param clazz

    * @param <T>

    * @return

    */

    public static <T> T getBean(String name, Class<T> clazz) {

        return getApplicationContext().getBean(name, clazz);

    }

  public static HttpServletRequest getRequest(){

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        return request;

    }

}

'''

相关文章

网友评论

    本文标题:SpringContextUtils

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