Spring容器-BeanFactory和ApplicationContext使用详解

作者:郝学胜 时间:2022-03-20 07:02:45 

将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<WebServerFactoryCustomizerBeanPostProcessor> webServerFactoryCustomizerBeanPostProcessor) {
       return new ServletWebServerFactoryCustomizer(
               webServerFactoryCustomizerBeanPostProcessor.getIfAvailable(Collections::emptyList));
   }
   @Bean
   @ConditionalOnMissingBean
   public TomcatServletWebServerFactory tomcatServletWebServerFactory(
           ObjectProvider<TomcatConnectorCustomizer> connectorCustomizers,
           ObjectProvider<TomcatContextCustomizer> 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<ConfigurableWebServerFactory> webServerFactoryCustomizer() {
   int port = environment.getProperty("server.port", Integer.class, 8080);
   return factory -> {
       factory.setPort(port);
   };
}
@Bean
public ServletWebServerFactory servletContainer() {
   return applicationContext.getBean(ServletWebServerFactory.class);
}

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

来源:https://juejin.cn/post/7225083372435357752

标签:Spring,BeanFactory,ApplicationContext,容器
0
投稿

猜你喜欢

  • 基于Spring的RPC通讯模型的使用与比较

    2022-04-22 01:18:18
  • 利用spring的拦截器自定义缓存的实现实例代码

    2022-07-22 00:44:47
  • C语言运用函数指针数组实现计算器功能

    2023-10-01 18:45:25
  • Java 批量文件压缩导出并下载到本地示例代码

    2023-04-15 07:29:30
  • Java全面深入探究SpringBoot拦截器与文件上传

    2021-11-12 20:08:24
  • openFeign服务之间调用保持请求头信息处理方式

    2022-11-07 23:45:21
  • IDEA设置背景为自定义照片的操作方法

    2022-12-28 09:13:08
  • 浅析12306售票算法(java版)

    2023-11-16 10:27:12
  • C#byte数组与Image的相互转换实例代码

    2023-08-15 16:15:51
  • Java switch使用原理及实例解析

    2023-10-11 20:44:20
  • 浅谈Java编程之if-else的优化技巧总结

    2023-06-02 23:28:12
  • 详解c# 中的DateTime

    2023-05-15 01:48:58
  • C# 实现颜色渐变窗体控件详细讲解

    2021-12-31 07:10:28
  • Spring Boot支持Crontab任务改造的方法

    2023-08-08 20:20:24
  • 自己动手写的mybatis分页插件(极其简单好用)

    2023-11-01 18:12:09
  • mybatis中sql语句CDATA标签的用法说明

    2021-08-08 14:14:49
  • C#实现导入CSV文件到Excel工作簿的方法

    2022-09-13 12:24:02
  • Java接口DAO模式代码原理及应用详解

    2023-06-21 05:29:04
  • Java修饰符 abstract,static,final 的区别详解

    2023-12-19 22:11:25
  • java音乐播放器编写源码

    2022-08-02 21:06:44
  • asp之家 软件编程 m.aspxhome.com