关于spring:Spring中获取bean的八种方式你get了几种

2次阅读

共计 5832 个字符,预计需要花费 15 分钟才能阅读完成。

1、在初始化时保留 ApplicationContext 对象

实用于 Spring 框架的独立应用程序,须要程序通过配置文件初始化 Spring。

applicationContext.xml配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="test" class="com.sxtx.bean.Test">
</bean>

</beans>

代码:

@Test
public void test() {ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    //ApplicationContext applicationContext = new FileSystemXmlApplicationContext("applicationContext.xml"); 
    Test test= (Test) applicationContext.getBean("test");
    System.out.println(test);
}

2、通过 Spring 提供的工具类获取 ApplicationContext 对象

适宜于 Spring 框架的 B / S 零碎,通过 ServletContext 对象获取 ApplicationContext 对象。而后在通过它获取须要的类实例。以下两个工具形式的差异是,前者在获取失败时抛出异样。后者返回 null。

ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc); 
ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc); 
ac1.getBean("beanId"); 
ac2.getBean("beanId");  

3、实现接口 ApplicationContextAware(举荐)

实现该接口的 setApplicationContext(ApplicationContext context) 办法,并保留 ApplicationContext 对象。Spring 初始化时,扫描到该类,就会通过该办法将ApplicationContext 对象注入。而后在代码中就能够获取 spring 容器 bean 了。

例如:

User bean = SpringUtils.getBean(“user”);

@Component
public class SpringUtils implements ApplicationContextAware {
 
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {SpringUtils.applicationContext = applicationContext;}
 
    public static <T> T getBean(String beanName) {if(applicationContext.containsBean(beanName)){return (T) applicationContext.getBean(beanName);
        }else{return null;}
    }
 
    public static <T> Map<String, T> getBeansOfType(Class<T> baseType){return applicationContext.getBeansOfType(baseType);
    }
}

4、继承自抽象类 ApplicationObjectSupport

调用父类的 getApplicationContext() 办法,获取 Spring 容器对象。

@Service
public class SpringContextHelper extends ApplicationObjectSupport {public Object getBean(String beanName) {return getApplicationContext().getBean(beanName);
    }
}

5、继承自抽象类 WebApplicationObjectSupport

调用 getWebApplicationContext() 获取WebApplicationContext

@Service
public class SpringContextHelper extends WebApplicationObjectSupport {public Object getBean(String beanName) {return getApplicationContext().getBean(beanName);
    }
}

6、应用 BeanFactory 间接获取(不举荐)

应用 BeanFactory 从工厂中间接获取 Bean 实例,然而 XmlBeanFactory 类曾经废除,因而不倡议应用。

@Test
public void test() {BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
    Test test= (Test) beanFactory.getBean("test");
    System.out.println(test);
}

7、应用 ContextLoader 提供的 getCurrentWebApplicationContext 办法

@Test
public void test() {MockServletContext sc = new MockServletContext("");
    sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "/applicationContext.xml");
    ServletContextListener listener = new ContextLoaderListener();
    ServletContextEvent event = new ServletContextEvent(sc);
    listener.contextInitialized(event);
    
    WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
    Test test= (Test) wac.getBean("test");
    System.out.println(test);
}

8、实现接口 BeanFactoryPostProcessor

spring 工具类 不便在非 spring 治理环境中获取 bean

@Component
public final class SpringUtilsS implements BeanFactoryPostProcessor
{
    /** Spring 利用上下文环境 */
    private static ConfigurableListableBeanFactory beanFactory;

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException
    {SpringUtilsS.beanFactory = beanFactory;}

    /**
     * 获取对象
     *
     * @param name
     * @return Object 一个以所给名字注册的 bean 的实例
     * @throws BeansException
     *
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) throws BeansException
    {return (T) beanFactory.getBean(name);
    }

    /**
     * 获取类型为 requiredType 的对象
     *
     * @param clz
     * @return
     * @throws BeansException
     *
     */
    public static <T> T getBean(Class<T> clz) throws BeansException
    {T result = (T) beanFactory.getBean(clz);
        return result;
    }

    /**
     * 如果 BeanFactory 蕴含一个与所给名称匹配的 bean 定义,则返回 true
     *
     * @param name
     * @return boolean
     */
    public static boolean containsBean(String name)
    {return beanFactory.containsBean(name);
    }

    /**
     * 判断以给定名字注册的 bean 定义是一个 singleton 还是一个 prototype。如果与给定名字相应的 bean 定义没有被找到,将会抛出一个异样(NoSuchBeanDefinitionException)*
     * @param name
     * @return boolean
     * @throws NoSuchBeanDefinitionException
     *
     */
    public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException
    {return beanFactory.isSingleton(name);
    }

    /**
     * @param name
     * @return Class 注册对象的类型
     * @throws NoSuchBeanDefinitionException
     *
     */
    public static Class<?> getType(String name) throws NoSuchBeanDefinitionException
    {return beanFactory.getType(name);
    }

    /**
     * 如果给定的 bean 名字在 bean 定义中有别名,则返回这些别名
     *
     * @param name
     * @return
     * @throws NoSuchBeanDefinitionException
     *
     */
    public static String[] getAliases(String name) throws NoSuchBeanDefinitionException
    {return beanFactory.getAliases(name);
    }

    /**
     * 获取 aop 代理对象
     * 
     * @param invoker
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T getAopProxy(T invoker)
    {return (T) AopContext.currentProxy();}
}

扩大

BeanFactoryApplicationContext 是 Spring 的两大外围接口,都能够当做 Spring 的容器。其中 ApplicationContextBeanFactory的子接口。

BeanFactory

(1)、是 Spring 外面最底层的接口(最原始的接口),蕴含了各种 Bean 的定义,读取 bean 配置文档,治理 bean 的加载、实例化,管制 bean 的生命周期,保护 bean 之间的依赖关系。

(2)、采纳的是提早加载模式来注入 Bean 的,即只有在应用到某个 Bean 时 (调用getBean()),才对该 Bean 进行加载实例化。这样,咱们就不能发现一些存在的 Spring 的配置问题。如果 Bean 的某一个属性没有注入,BeanFacotry 加载后,直至第一次应用调用 getBean 办法才会抛出异样。

(3)BeanFactory通常以编程的形式被创立。

(4)BeanFactoryApplicationContext 都反对 BeanPostProcessorBeanFactoryPostProcessor 的应用,但两者之间的区别是:BeanFactory须要手动注册,而 ApplicationContext 则是主动注册。

(5)占用内存小。

ApplicationContext

1、ApplicationContext接口作为 BeanFactory 的派生,除了提供 BeanFactory 所具备的性能外,还提供了更残缺的框架性能:

  • 继承MessageSource,因而反对国际化。
  • 对立的资源文件拜访形式。
  • 提供在监听器中注册 bean 的事件。
  • 同时加载多个配置文件。
  • 载入多个(有继承关系)上下文,使得每一个上下文都专一于一个特定的档次,比方利用的 web 层。

2、ApplicationContext,它是在容器启动时,一次性创立了所有的 Bean。这样,在容器启动时,咱们就能够发现 Spring 中存在的配置谬误,这样有利于查看所依赖属性是否注入。ApplicationContext启动后预载入所有的单实例 Bean,通过预载入单实例 bean,确保当你须要的时候,你就不必期待,因为它们曾经创立好了。

3、ApplicationContext 占用内存空间大,当程序的配置 bean 特地多时,程序启动慢。

4、ApplicationContext 能以编程式形式创立,还能能以申明的形式创立,如应用ContextLoader

正文完
 0