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>

代码:

@Testpublic 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”);
@Componentpublic 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容器对象。

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

5、继承自抽象类WebApplicationObjectSupport

调用getWebApplicationContext()获取WebApplicationContext

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

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

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

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

7、应用ContextLoader提供的getCurrentWebApplicationContext办法

@Testpublic 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

@Componentpublic 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