• Spring Boot中普通类获取Spring容器中的Bean


    我们知道如果我们要在一个类使用spring提供的bean对象,我们需要把这个类注入到spring容器中,交给spring容器进行管理,但是在实际当中,我们往往会碰到在一个普通的Java类中,自己动手new的对象,想直接使用spring提供的其他对象或者说有一些不需要交给spring管理,但是需要用到spring里的一些对象;

    虽然通过

    ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContext.xml");
    
    ac.getBean("beanId") 
    

    方式加载xml文件来获取上下文环境获得bean,但由于在web application中,spring是通过web.xml加载配置的,所有会加载两次spring容器,同时在spring boot中一般是无xml配置的,所以需要其他方式了;

    1.通过实现 ApplicationContextAware接口 定义一个SpringUtil工具类,实现ApplicationContextAware接口

     1 public class SpringUtil implements ApplicationContextAware { 
     2 private static ApplicationContext applicationContext; 
     3 
     4     @Override 
     5     public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
     6         if(SpringUtil.applicationContext == null) { 
     7             SpringUtil.applicationContext = applicationContext; 
     8         } 
     9     } 
    10 
    11     //获取applicationContext 
    12     public static ApplicationContext getApplicationContext() { 
    13         return applicationContext; 
    14     } 
    15 
    16     //通过name获取 Bean. 
    17     public static Object getBean(String name){ 
    18         return getApplicationContext().getBean(name); 
    19     } 
    20 
    21     //通过class获取Bean. 
    22     public static T getBean(Class clazz){ 
    23         return getApplicationContext().getBean(clazz); 
    24     } 
    25 
    26     //通过name,以及Clazz返回指定的Bean 
    27     public static T getBean(String name,Class clazz){ 
    28         return getApplicationContext().getBean(name, clazz); 
    29     } 
    30 }    
  • 相关阅读:
    js对象深拷贝
    数组去重
    css布局之双飞翼布局
    css布局之圣杯布局
    在浏览器中输入URL并回车后都发生了什么?
    浮动和清除浮动
    Javascript 构造函数模式、原型模式
    Javascript之对象组合继承
    js可以随意拖拽的div的实现
    博客美化 之博客的魔方效果
  • 原文地址:https://www.cnblogs.com/canda/p/7835790.html
Copyright © 2020-2023  润新知