Spring容器-BeanFactory和ApplicationContext使用详解

 更新时间:2023年04月24日 08:53:34   作者:郝学胜  
这篇文章主要为大家介绍了Spring容器-BeanFactory和ApplicationContext的使用示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

将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实例。

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

以上就是Spring容器-BeanFactory和ApplicationContext使用详解的详细内容,更多关于Spring BeanFactory ApplicationContext的资料请关注脚本之家其它相关文章!

相关文章

  • Spring之InitializingBean接口和DisposableBean接口的使用

    Spring之InitializingBean接口和DisposableBean接口的使用

    这篇文章主要介绍了Spring之InitializingBean接口和DisposableBean接口的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-01-01
  • java中String,数组,ArrayList三者之间的转换

    java中String,数组,ArrayList三者之间的转换

    这篇文章主要介绍了java中String,数组,ArrayList三者之间的转换,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-01-01
  • Mybatis自定义拦截器实现权限功能

    Mybatis自定义拦截器实现权限功能

    本文主要介绍了Mybatis自定义拦截器实现权限功能,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2024-12-12
  • Java实现简单的邮件发送功能

    Java实现简单的邮件发送功能

    这篇文章主要为大家详细介绍了Java实现简单的邮件发送功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-07-07
  • SpringBoot使用Redis实现消息队列的方法小结

    SpringBoot使用Redis实现消息队列的方法小结

    在应用中把Redis当成消息队列来使用已经屡见不鲜了,我想主要原因是当代应用十有八九都会用到 Redis,因此不用再引入其他消息队列系统,而且Redis提供了好几种实现消息队列的方法,用起来也简单,本文给大家介绍了SpringBoot使用Redis实现消息队列的方法小结
    2024-04-04
  • 如何使用Spring自定义Xml标签

    如何使用Spring自定义Xml标签

    要实现自定义的xml配置,需要有两个默认spring配置文件来支持。一个是spring.schemas,一个是spring.handlers,前者是为了验证你自定义的xml配置文件是否符合你的格式要求,后者是告诉spring该如何来解析你自定义的配置文件。本文将介绍如何使用Spring自定义Xml标签
    2021-06-06
  • Java泛型和Class类用法示例

    Java泛型和Class类用法示例

    这篇文章主要介绍了Java泛型和Class类用法,结合实例形式分析了java使用泛型限制class类避免强制类型转换相关操作技巧,需要的朋友可以参考下
    2019-07-07
  • SpringBoot接入deepseek深度求索示例代码(jdk1.8)

    SpringBoot接入deepseek深度求索示例代码(jdk1.8)

    这篇文章主要介绍了SpringBoot接入deepseek深度求索的相关资料,包括建API key、封装询问Deepseek的工具方法(在配置文件中添加key值)、调用测试并确保端口一致例如8091,最后运行结果,需要的朋友可以参考下
    2025-02-02
  • SpringBoot中使用MyBatis-Plus详细步骤

    SpringBoot中使用MyBatis-Plus详细步骤

    MyBatis-Plus是MyBatis的增强工具,简化了MyBatis的使用,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友跟随小编一起看看吧
    2025-01-01
  • 一文搞懂Spring Security异常处理机制

    一文搞懂Spring Security异常处理机制

    这篇文章主要为大家详细介绍一下Spring Security异常处理机制,文中的示例代码讲解详细,对我们学习Spring Security有一定帮助,感兴趣的可以学习一下
    2022-07-07

最新评论