`
zengshaotao
  • 浏览: 778244 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

spring加载完bean之后执行相关初始化

 
阅读更多

spring是j2ee比较常用的开源技术,集成spring只需在应用的web.xml文件中进行如下配置:
<!--spring在应用中的全局参数-->

<context-param>
<param-name>contextConfigLocation</param-name>

<!--支持classpath协议,便于多文件的配置-->
<param-value>classpath*:spring/**.spring.xml</param-value>
</context-param>
<!-- 启动spring容器的监听器-->
<listener>
<listenerclass>
                org.springframework.web.context.ContextLoaderListener
        </listener-class>
</listener>
初始化spring/**.spring.xml文件中配置的bean对象、初始化国际化相关的对象(MessageSource)等许多初始化工作就是在ContextLoaderListener中完成,当这些步骤执行完后就是执行刷新上下文事件,详细解析如下:

if (this.context == null) {

this.context = createWebApplicationContext(servletContext);

}

if (this.context instanceof ConfigurableWebApplicationContext) {

configureAndRefreshWebApplicationContext((ConfigurableWebApplicationContext)this.context, servletContext);

 

}

对于createWebApplicationContext方法:

protected WebApplicationContext createWebApplicationContext(ServletContext sc) {

Class<?> contextClass = determineContextClass(sc);

if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {

throw new ApplicationContextException("Custom context class [" + contextClass.getName() +

"] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");

}

ConfigurableWebApplicationContext wac =

(ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);

return wac;

 

}

 

所以会走configureAndRefreshWebApplicationContext方法,该方法的结尾就有如下代码:

customizeContext(sc, wac);

 

wac.refresh();

ConfigurableWebApplicationContext 是一个接口,其抽象实现类是:AbstractApplicationContext类

其中的refresh方法:

synchronized (this.startupShutdownMonitor) {

// Prepare this context for refreshing.

prepareRefresh();

 

// Tell the subclass to refresh the internal bean factory.

ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

 

// Prepare the bean factory for use in this context.

prepareBeanFactory(beanFactory);

 

try {

// Allows post-processing of the bean factory in context subclasses.

postProcessBeanFactory(beanFactory);

 

// Invoke factory processors registered as beans in the context.

invokeBeanFactoryPostProcessors(beanFactory);

 

// Register bean processors that intercept bean creation.

registerBeanPostProcessors(beanFactory);

 

// Initialize message source for this context.

initMessageSource();

 

// Initialize event multicaster for this context.

initApplicationEventMulticaster();

 

// Initialize other special beans in specific context subclasses.

onRefresh();

 

// Check for listener beans and register them.

registerListeners();

 

// Instantiate all remaining (non-lazy-init) singletons.

finishBeanFactoryInitialization(beanFactory);

 

// Last step: publish corresponding event.

finishRefresh();

}

 

catch (BeansException ex) {

// Destroy already created singletons to avoid dangling resources.

destroyBeans();

 

// Reset 'active' flag.

cancelRefresh(ex);

 

// Propagate exception to caller.

throw ex;

}

}


/**
* Finish the refresh of this context, invoking the LifecycleProcessor's
* onRefresh() method and publishing the
* {@link org.springframework.context.event.ContextRefreshedEvent}.
*/

protected void finishRefresh() {

// Initialize lifecycle processor for this context.

initLifecycleProcessor();

 

// Propagate refresh to lifecycle processor first.

getLifecycleProcessor().onRefresh();

 

// Publish the final event.

publishEvent(new ContextRefreshedEvent(this));

}

 

发现publishEvent(new ContextRefreshedEvent(this));这行代码就是发布上下文的事件,我们可自己定义一个监听器让其实现ApplicationListener接口,覆盖onApplicationEvent方法,在onApplicationEvent方法中编写想关的业务逻辑:代码如下:

public class custContextListener implements ApplicationListener {
public void onApplicationEvent(ApplicationEvent event) {
if(event instanceof ContextRefreshedEvent) {

}
}
}

分享到:
评论

相关推荐

    详解Spring 中如何控制2个bean中的初始化顺序

    Spring 中控制 2 个 bean 的初始化顺序 在 Spring 框架中,控制多个 bean 的初始化顺序是一个常见的问题。本篇文章将详细介绍如何控制 2 个 bean 的初始化顺序,提供了多种实现方式,并分析了每种方式的优缺。 ...

    Spring Bean创建初始化流程.docx

    9. **Bean初始化**: 最后,`initializeBean(beanName, exposedObject, mbd)`对创建好的Bean进行初始化,包括调用初始化方法(如果有`@PostConstruct`注解的方法),以及执行AOP代理等操作。 整个流程中,Spring...

    springBean加载过程源码解析文档,附有代码类名和行数

    Spring Bean 加载过程是 Spring 框架中最核心的部分之一,涉及到 ApplicationContext 的初始化、Bean 的加载和注册等过程。在 Spring Boot 应用程序中,SpringApplication 负责加载和管理 Bean。 SpringApplication...

    spring的bean加载顺序样例项目

    在Spring框架中,Bean的加载顺序是一个重要的概念,它涉及到Spring容器如何管理和初始化Bean的过程。在"spring的bean加载顺序样例项目"中,我们可以通过分析和实验来深入理解这一主题。下面将详细阐述Spring Bean的...

    Spring Bean重复执行两次(实例被构造两次)问题分析

    3. **@PostConstruct与初始化回调**:Spring允许我们在Bean初始化后执行特定代码,通常通过`@PostConstruct`注解的方法来实现。如果这个方法被意外地调用了两次,那么Bean也会被构造两次。检查是否有多处调用或配置...

    Spring Bean 加载顺序 .

    7. **Bean初始化**: 实例化完成后,Spring会执行Bean的初始化方法,包括调用`@PostConstruct`注解的方法。同时,如果Bean实现了InitializingBean接口,其`afterPropertiesSet()`方法也会被调用。 8. **初始化后...

    Spring bean 动态注册,jar包热替换

    Spring bean 一般通过配置文件和注解进行加载,如果要实现jar或class...测试示例中是spring boot 的部分代码,动态加载的内容为接口实现类,且初始化时加载本地的实现类,动态加载后改为非程序加载目录中的jar实现类。

    详解Spring简单容器中的Bean基本加载过程

    3. 加载 bean:Spring 会加载 bean,并将其实例化。 4. 获取 bean:应用程序可以从容器中获取 bean 并使用它。 在加载 bean 的过程中,Spring 会使用 Resource 对象来表示 XML 文件,然后使用 ...

    Spring源码学习六:bean初始化1

    在本篇文章中,我们将深入探讨Spring源码中关于Bean初始化的过程,特别是`finishBeanFactoryInitialization()`方法和`preInstantiateSingletons()`方法。 首先,`finishBeanFactoryInitialization(Confi‌...

    Spring動態加載Bean

    在Spring框架中,动态加载Bean是一项重要的功能,它允许我们在运行时根据需要加载或卸载Bean,而不是在应用启动时一次性加载所有Bean。这对于处理不同环境、减少内存占用或者实现按需服务的情况非常有用。本篇文章将...

    Spring 源码分析(Bean的初始化)

    总结起来,Spring的Bean初始化是一个复杂而精细的过程,涉及XML解析、BeanDefinition的构建、依赖注入、初始化回调、AOP代理等多个环节。通过深入理解这一过程,开发者能更好地掌握Spring框架的工作原理,从而更高效...

    Spring中与Bean相关的接口

    实现了`InitializingBean`的Bean会在初始化之后自动调用`afterPropertiesSet()`方法,用于执行初始化逻辑。而实现了`DisposableBean`的Bean会在容器关闭时调用`destroy()`方法,执行清理工作。然而,这两种接口的...

    spring加载顺序讨论

    1. **@PostConstruct注解**:在Bean实例化后,初始化之前,Spring会查找方法上标注了`@PostConstruct`的非静态方法,并在所有依赖注入完成后调用,用于执行初始化逻辑。这个注解可以确保在Bean完全准备就绪并可以...

    spring bean XML配置入门

    一旦XML配置加载到Spring容器中,容器将根据配置创建Bean实例,并按照定义进行初始化、依赖注入,最后完成Bean的生命周期管理。 10. **实践操作**: 在实际开发中,我们可以使用Eclipse的Spring插件来简化Bean...

    spring IOC反射装载bean

    比如,当配置了初始化方法或销毁方法,Spring会在适当的时候调用这些方法。例如: ```xml &lt;bean id="myBean" class="com.example.MyClass" init-method="initMethod"&gt; ... &lt;/bean&gt; ``` 这里,`init-method`指定的...

    Spring Boot 全局懒加载机制.docx

    在Spring框架中,bean的默认行为是在应用启动时创建并初始化。然而,有时我们希望某些bean在实际需要时才进行初始化,这就是所谓的“懒加载”(Lazy Initialization)。Spring Boot 2.2及更高版本引入了一个全局懒...

    让spring解决控制springboot中bean的加载顺序的问题.docx

    在Spring Boot应用中,控制Bean的加载顺序是一个关键的议题,尤其是在处理复杂依赖关系或需要在特定时刻执行初始化操作的场景。Spring Boot遵循"约定优于配置"的理念,简化了配置,但同时也带来了需要手动干预Bean...

    spring bean的生命周期

    - **初始化回调**:Spring支持两种类型的初始化回调方法,即`@PostConstruct`注解的方法和在XML中定义的`init-method`属性指定的方法。 2. **容器管理的生命周期回调** - **Singleton Beans的懒加载**:如果Bean...

    spring注解开发--Bean加载控制.zip

    这两个注解标记方法分别在bean初始化后和销毁前执行,提供生命周期回调功能。 9. **@Configuration 和 @Bean** 虽然我们主要讨论的是注解驱动的开发,但`@Configuration`和`@Bean`也值得一提。这两个注解提供了...

    Spring中关于Bean的管理的课件

    9. **加载Bean的方式**:Spring支持多种方式加载Bean,包括XML配置文件、基于注解的配置和Java配置类。 10. **Aware接口**:Spring提供了一系列的Aware接口,如BeanNameAware、BeanFactoryAware和...

Global site tag (gtag.js) - Google Analytics