• 面试官:Spring中获取Bean有几种方式?


    前两天,有位同学在面试中被问了: Spring中获取Bean有几种方式?

    为了悲剧不在上演,今天给大家安排。

    一共七种方式

    1、使用 BeanFactory 直接获取(不推荐)

    2、在初始化时保存 ApplicationContext 对象

    3、继承自抽象类 ApplicationObjectSupport

    4、继承自抽象类 WebApplicationObjectSupport

    5、使用Spring提供的工具类 WebApplicationContextUtils

    6、实现 ApplicationContextAware 接口

    7、使用 ContextLoader 提供的 getCurrentWebApplicationContext() 方法

    面试遇到了把这七种方式说完就行,其实只要你能记住三五种,面试官也是认可你的。

    可是,不好记呀,对么?怎么办?

    下面,田哥给你整理好了每个方式的对应案例。

    一.使用BeanFactory直接获取(不推荐)

    使用 BeanFactory 从工厂中直接获取Bean实例,但是 XmlBeanFactory 类已经废弃,因此不建议使用,测试代码如下:

    1. /**
    2. * 方式一:XmlBeanFactory已经废弃不建议使用
    3. */
    4. @Test
    5. public void getBeanTest1() {
    6. BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
    7. UserInfo userInfo = (UserInfo) beanFactory.getBean("userInfo");
    8. System.out.println(userInfo);
    9. }

    二.在初始化时保存ApplicationContext对象

    可以在初始化的时候保存 ApplicationContext 对象,然后通过这个对象获取Bean,测试代码如下:

    1. /**
    2. * 方式二:使用ClassPathXmlApplicationContext获取ApplicationContext
    3. */
    4. @Test
    5. public void getBeanTest2() {
    6. ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    7. UserInfo userInfo = (UserInfo) applicationContext.getBean("userInfo");
    8. System.out.println(userInfo);
    9. }

    三.继承自抽象类ApplicationObjectSupport

    可以继承抽象类 ApplicationObjectSupport 并将自己继承的类注入到Spring容器中,示例代码如下:

    1. /**
    2. * 方法三:继承ApplicationObjectSupport来获取ApplicationContext,
    3. * 注意:需要把自己继承的类注入到Spring
    4. */
    5. @Test
    6. public void getBeanTest3() {
    7. ApplicationContextUtil2 applicationContextUtil2 = (ApplicationContextUtil2) ApplicationContextUtil.getBean("applicationContextUtil2");
    8. UserInfo userInfo = (UserInfo) applicationContextUtil2.getBean("userInfo");
    9. System.out.println(userInfo);
    10. }

    其中 ApplicationContextUtil2 的代码如下所示:

    1. public class ApplicationContextUtil2 extends ApplicationObjectSupport {
    2. /**
    3. * 通过bean的id获取bean对象
    4. * @param beanName
    5. * @return
    6. */
    7. public Object getBean(String beanName){
    8. return super.getApplicationContext().getBean(beanName);
    9. }
    10. }

    最后莫忘了将Bean注入到Spring容器中,通过注解,或者配置均可,本示例通过配置实现

    1. <bean id="applicationContextUtil2" class="com.leo.util.ApplicationContextUtil2">bean>

    四.继承自抽象类WebApplicationObjectSupport

    可以继承抽象类 WebApplicationObjectSupport 并将自己继承的类注入到Spring容器中,示例代码如下:

    1. /**
    2. * 方法四:继承WebApplicationObjectSupport来获取ApplicationContext,
    3. * 注意:需要把自己继承的类注入到Spring,同时需要添加@WebAppConfiguration注解,否则会找不到web容器
    4. */
    5. @Test
    6. public void getBeanTest4() {
    7. ApplicationContextUtil3 applicationContextUtil3 = (ApplicationContextUtil3) ApplicationContextUtil.getBean("applicationContextUtil3");
    8. UserInfo userInfo = (UserInfo) applicationContextUtil3.getBean("userInfo");
    9. System.out.println(userInfo);
    10. }

    其中 ApplicationContextUtil3 的示例代码如下:

    1. public class ApplicationContextUtil3 extends WebApplicationObjectSupport{
    2. /**
    3. * 通过bean的id获取bean对象
    4. * @param beanName
    5. * @return
    6. */
    7. public Object getBean(String beanName){
    8. return super.getWebApplicationContext().getBean(beanName);
    9. }
    10. }

    最后莫忘了将Bean注入到Spring容器中,通过注解,或者配置均可,本示例通过配置实现

    1. <bean id="applicationContextUtil3" class="com.leo.util.ApplicationContextUtil3">bean>

    五.使用Spring提供的工具类WebApplicationContextUtils

    使用Spring提供的工具类 WebApplicationContextUtils 来获取 WebApplicationContext 对象,这个方法很常见于SpringMVC构建的web项目中,测试代码如下所示:

    1. /**
    2. * 方法五:使用WebApplicationContextUtils提供的方法获取ApplicationContext对象
    3. */
    4. @Test
    5. public void getBeanTest5(){
    6. //模拟ServletContext上下文,不然会出现空指针异常
    7. MockServletContext sc = new MockServletContext("");
    8. sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "/applicationContext.xml");
    9. ServletContextListener listener = new ContextLoaderListener();
    10. ServletContextEvent event = new ServletContextEvent(sc);
    11. listener.contextInitialized(event);
    12. //使用WebApplicationContextUtils的getRequiredWebApplicationContext方法
    13. WebApplicationContext webApplicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
    14. UserInfo userInfo = (UserInfo) webApplicationContext.getBean("userInfo");
    15. System.out.println(userInfo);
    16. //使用WebApplicationContextUtils的getWebApplicationContext方法
    17. WebApplicationContext webApplicationContext2 = WebApplicationContextUtils.getWebApplicationContext(sc);
    18. UserInfo userInfo2 = (UserInfo) webApplicationContext2.getBean("userInfo");
    19. System.out.println(userInfo2);
    20. }

    六.实现ApplicationContextAware接口

    通过实现 ApplicationContextAware 接口,在Spring容器启动的时候将 ApplicationContext 注入进去,从而获取 ApplicationContext 对象,这种方法也是常见的获取Bean的一种方式,测试代码如下:

    1. /**
    2. *方法六:实现ApplicationContextAware接口获取ApplicationContext
    3. */
    4. @Test
    5. public void getBeanTest6(){
    6. UserInfo userInfo2 = (UserInfo) ApplicationContextUtil.getBean("userInfo");
    7. System.out.println(userInfo2);
    8. }

    其中 ApplicationContextUtil 的实现如下:

    1. public class ApplicationContextUtil implements ApplicationContextAware{
    2. private static ApplicationContext applicationContext;
    3. /**
    4. * 通过bean的id获取bean对象
    5. * @param beanName
    6. * @return
    7. */
    8. public static Object getBean(String beanName){
    9. return applicationContext.getBean(beanName);
    10. }
    11. /**
    12. * 根据bean的id和类型获取bean对象
    13. * @param beanName
    14. * @param clazz
    15. * @param
    16. * @return
    17. */
    18. public static T getBean(String beanName,Class clazz){
    19. return clazz.cast(getBean(beanName));
    20. }
    21. @Override
    22. public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    23. this.applicationContext = applicationContext;
    24. }
    25. }

    七.使用ContextLoader提供的getCurrentWebApplicationContext方法

    使用 ContextLoader 提供的 getCurrentWebApplicationContext 方法提供的方法也是常用的获取 WebApplicationContext 的一种方法,这个方法常见于SpringMVC实现的web项目中。

    测试代码如下:

    1. /**
    2. * 方法七:使用ContextLoader的getCurrentWebApplicationContext方法获取WebApplicationContext
    3. */
    4. @Test
    5. public void getBeanTest7() {
    6. MockServletContext sc = new MockServletContext("");
    7. sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "/applicationContext.xml");
    8. ServletContextListener listener = new ContextLoaderListener();
    9. ServletContextEvent event = new ServletContextEvent(sc);
    10. listener.contextInitialized(event);
    11. //如果不加上面的模拟创建ServletContext对象,会报空指针异常
    12. WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
    13. UserInfo userInfo = (UserInfo) wac.getBean("userInfo");
    14. System.out.println(userInfo);
    15. }

    这么一顿操作下来,是不是印象更深了?

    再回头想想,有几种方式?你记住几种?

    好了,今天就分享到这里。

  • 相关阅读:
    电容笔哪个牌子好?2022年电容笔十大品牌排行榜
    【Java SE】面向对象、类和对象详解
    C++多线程01
    C++类的自动类型转换和强制类型转换
    DIXml v5.21.0 for Delphi 11
    Hadoop FS 文件系统命令
    布隆过滤器
    Mybatis学习笔记9 动态SQL
    Vulnhub靶机:GEMINI INC_ 2
    linux系统编程(六) linux文件系统的操作
  • 原文地址:https://blog.csdn.net/Trouvailless/article/details/126703096