likes
comments
collection
share

Spring容器-BeanFactory和ApplicationContext

作者站长头像
站长
· 阅读数 11

将BeanFactory和ApplicationContext作为容器使用

在Spring中,BeanFactory和ApplicationContext是容器的两种实现方式,可以使用它们来管理对象的生命周期以及实现依赖注入等功能。下面我们来分别演示一下BeanFactory和ApplicationContext子类的使用方式。

BeanFactory容器

BeanFactory是Spring容器中最基本的接口,它提供了定义和管理bean的基本方式。使用BeanFactory容器的步骤如下:

1.定义一个Bean对象

public class HelloBean { 
   private String message; 
   public void setMessage(String message) { 
      this.message = message; 
   } 
   public void sayHello() { 
      System.out.println("Hello " + message); 
   } 
} 

2.在Spring的配置文件中声明一个bean对象

<beans> 
    <bean id="helloBean" class="com.example.HelloBean"> 
        <property name="message" value="World" /> 
    </bean>
</beans>

3.使用BeanFactory容器获取bean对象

BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("beans.xml")); 
HelloBean helloBean = (HelloBean) beanFactory.getBean("helloBean"); 
helloBean.sayHello(); 

ApplicationContext容器

ApplicationContext是BeanFactory的子接口,它是Spring容器的另一种实现方式。和BeanFactory容器相比,ApplicationContext容器提供了更加丰富的功能,例如国际化支持、事件发布、资源管理等。使用ApplicationContext容器的步骤如下: 1.定义一个Bean对象

public class HelloBean { 
    private String message; 
    public void setMessage(String message) { 
       this.message = message; 
    } 
    public void sayHello() { 
       System.out.println("Hello " + message); 
    } 
} 

2.在Spring的配置文件中声明一个bean对象

<beans> 
    <bean id="helloBean" class="com.example.HelloBean"> 
        <property name="message" value="World" />
    </bean>
</beans> 

3.使用ApplicationContext容器获取bean对象

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml"); 
HelloBean helloBean = (HelloBean) applicationContext.getBean("helloBean"); 
helloBean.sayHello(); 

Spring内嵌Web容器的过程

在Spring中,ApplicationContext容器有多个子类,其中包括了用于WEB开发的子类。这些子类可以直接启动Tomcat、Jetty等Web容器,使得我们可以在不使用第三方Web容器的情况下,直接在Spring应用内启动Web应用。下面以SpringBoot的Web容器启动为例,来说明ApplicationContext子类的具体源代码实现过程。 我们先来看一下SpringBoot的启动类:

@SpringBootApplication 
public class Application { 
    public static void main(String[] args) { 
       SpringApplication.run(Application.class, args); 
    } 
} 

在这个启动类中,我们使用了SpringBoot提供的@SpringBootApplication注解。这个注解是一个组合注解,包含了多个其他注解,其中一个注解就是@Import({ ServletWebServerFactoryAutoConfiguration.class, WebMvcAutoConfiguration.class })。这个注解的作用是向Spring容器中注册两个自动配置类:ServletWebServerFactoryAutoConfiguration和WebMvcAutoConfiguration。

接着我们来看一下ServletWebServerFactoryAutoConfiguration这个类:

@Configuration(proxyBeanMethods = false)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass(Servlet.class)
@ConditionalOnMissingBean(value = { ServletWebServerFactory.class, WebServerFactoryCustomizerBeanPostProcessor.class })
public class ServletWebServerFactoryAutoConfiguration {

    @Bean
    public ServletWebServerFactoryCustomizer servletWebServerFactoryCustomizer(
            ObjectProvider&lt;WebServerFactoryCustomizerBeanPostProcessor&gt; webServerFactoryCustomizerBeanPostProcessor) {
        return new ServletWebServerFactoryCustomizer(
                webServerFactoryCustomizerBeanPostProcessor.getIfAvailable(Collections::emptyList));
    }

    @Bean
    @ConditionalOnMissingBean
    public TomcatServletWebServerFactory tomcatServletWebServerFactory(
            ObjectProvider&lt;TomcatConnectorCustomizer&gt; connectorCustomizers,
            ObjectProvider&lt;TomcatContextCustomizer&gt; contextCustomizers, Environment environment) {
        TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
        factory.setEnvironment(environment);
        factory.setTomcatConnectorCustomizers(connectorCustomizers.orderedStream().collect(Collectors.toList()));
        factory.setTomcatContextCustomizers(contextCustomizers.orderedStream().collect(Collectors.toList()));
        return factory;
    }

}

可以看到,这个类标记为@Configuration注解,表示它是一个配置类。这个类提供了TomcatServletWebServerFactory这个bean定义,它利用Tomcat作为Web容器。这个类还提供了一个servletWebServerFactoryCustomizer的bean定义,它会在Web容器启动前对Web容器进行自定义的配置。

除了ServletWebServerFactoryAutoConfiguration之外,还有一些其他的自动配置类。例如:

  • HttpEncodingAutoConfiguration:自动配置请求和响应的编码过滤器。
  • DispatcherServletAutoConfiguration:自动配置一个DispatcherServlet,它用于处理Web请求。

在SpringBoot启动时,会将这些自动配置类都加载到Spring容器中。最终,我们就可以使用ApplicationContext容器来获取Web容器实例,代码如下:

@Bean
public WebServerFactoryCustomizer&lt;ConfigurableWebServerFactory&gt; webServerFactoryCustomizer() {
    int port = environment.getProperty("server.port", Integer.class, 8080);
    return factory -&gt; {
        factory.setPort(port);
    };
}

@Bean
public ServletWebServerFactory servletContainer() {
    return applicationContext.getBean(ServletWebServerFactory.class);
}

可以看到,这个代码中直接调用了ApplicationContext容器的getBean方法,来获取ServletWebServerFactory这个bean实例。

以上就是一个简单的说明Spring内嵌Web容器的过程。在实际的项目中,我们也可以使用ApplicationContext容器来启动其他的Web容器,例如Jetty等。总的来说,Spring内嵌Web容器的使用非常的方便,适合于小型的Web应用的快速开发。