Spring容器加载完之后执行特定任务

Spring容器与初始化任务分离实践
[url]http://my.oschina.net/simpleton/blog/692799[/url]
有两个服务器类,需要SpringContext在InitAfterSpringContextService之前初始化:

1、SpringContext

spring容器的上线文环境

package com.cdelabcare.pubservice;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

/**
* Spring上下文环境
*/
@Service
public class SpringContext implements ApplicationContextAware {

/** Spring应用上下文环境 */
private static ApplicationContext applicationContext;

/**
* 实现ApplicationContextAware接口的回调方法,设置上下文环境
* <pre>
* 当spring容器加载完后会触发该方法
* </pre>
* @param applicationContext {@link ApplicationContext}
* @throws BeansException
*/
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContext.applicationContext = applicationContext;

}

/**
* @return ApplicationContext
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}

/**
* 获取对象
*
* @param name
* @return Object 一个以所给名字注册的bean的实例
* @throws BeansException
*/
public static Object getBean(String name) throws BeansException {
return applicationContext.getBean(name);
}

/**
* 获取类型为requiredType的对象
* 如果bean不能被类型转换,相应的异常将会被抛出(BeanNotOfRequiredTypeException)
*
* @param name
* bean注册名
* @param requiredType
* 返回对象类型
* @return Object 返回requiredType类型对象
* @throws BeansException
*/
public static <T> T getBean(String name, Class<T> requiredType) throws BeansException {
return applicationContext.getBean(name, requiredType);
}
}



2、InitAfterSpringContextService

在Spring初始化完成之后执行一些初始化任务(需要在SpringContext执行完成之后执行)

package com.cdelabcare.service.serviceutil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;

import com.cdelabcare.pubservice.SpringContext;

/**
* 初始化Spring完成之后的操作
* @create pengjunhao
* @createDate 2016年6月16日 上午10:06:11
* @update
* @updateDate
*/
@Service
public class InitAfterSpringContextService implements ApplicationListener<ContextRefreshedEvent> {

/** 日志 */
private static final Logger LOGGER = LoggerFactory
.getLogger(InitAfterSpringContextService.class);

/** 引入SpringContext的依赖,主要为了让SpringContext优先加载 */
@Autowired
private SpringContext springContext;

/*
* 监听事件
* @see org.springframework.context.ApplicationListener#onApplicationEvent(org.springframework.context.ApplicationEvent)
*/
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
//root application context 没有parent
if (event.getApplicationContext().getParent() == null) {
LOGGER.info("【初始化事务....】");
// TODO something
}
}

}

通过使用implements ApplicationListener<ContextRefreshedEvent>可以监听spring容器是否初始化完成。
### Spring IOC 容器加载流程解析 Spring IOC(Inversion of Control)容器Spring框架的核心组件之一,它负责管理应用程序中的对象及其依赖关系。以下是Spring IOC容器加载流程的详细解析: #### 1. 创建Spring容器实例 Spring IOC容器加载过程始于创建容器实例。通常使用`ApplicationContext`接口来创建容器,例如通过`ClassPathXmlApplicationContext`或`AnnotationConfigApplicationContext`等方式实现[^2]。这一阶段的主要任务是初始化容器环境并准备加载配置。 #### 2. 加载配置文件或注解 在容器实例化后,Spring会根据配置文件(如XML文件)或注解(如`@Component`、`@Configuration`等)来读取Bean定义信息。对于基于注解的方式,Spring会扫描指定的包路径,查找带有特定注解的类,并将它们注册为Bean定义[^3]。 ```java // 示例:基于注解的Bean定义 import lombok.Getter; import lombok.Setter; import org.springframework.stereotype.Component; @Getter @Setter @Component public class DemoBeanA { private String name; } ``` #### 3. 注册Bean定义 Spring IOC容器会将读取到的Bean定义信息注册到内部的数据结构中,通常是`DefaultListableBeanFactory`中的一个`Map`结构。这个阶段成后,所有的Bean定义信息已经被容器捕获并存储[^1]。 #### 4. Bean的实例化与依赖注入 在所有Bean定义被注册后,Spring开始实例化这些Bean。根据Bean的作用域(如`singleton`或`prototype`),容器会选择合适的时机创建Bean实例。同时,Spring会根据依赖关系自动成Bean之间的注入操作,确保每个Bean都能正确获取其所需的依赖项[^2]。 #### 5. 初始化Bean 在Bean实例化和依赖注入成后,Spring会调用Bean的初始化方法(如通过`@PostConstruct`注解标记的方法或实现了`InitializingBean`接口的`afterPropertiesSet`方法)。这一阶段允许开发者对Bean进行额外的初始化操作。 #### 6. 销毁Bean 当应用程序关闭时,Spring会调用Bean的销毁方法(如通过`@PreDestroy`注解标记的方法或实现了`DisposableBean`接口的`destroy`方法)。这一步骤确保资源能够被正确释放。 --- ### Spring IOC 容器加载流程图解析 以下是一个简化的Spring IOC容器加载流程图,展示了各个阶段的主要任务: ``` +-------------------+ +---------------------+ +------------------+ | 创建容器实例 | ----> | 加载配置文件/注解 | ----> | 注册Bean定义 | +-------------------+ +---------------------+ +------------------+ | v +------------------+ +-------------------+ +-----------------+ | 实例化Bean | ----> | 依赖注入 | ----> | 初始化Bean | +------------------+ +-------------------+ +-----------------+ | v +------------------+ | 销毁Bean | +------------------+ ``` --- ### 示例代码:Spring IOC容器加载过程 以下是一个简单的Spring应用示例,展示IOC容器加载流程: ```java import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.ComponentScan; import org.springframework.stereotype.Component; @Component class MyBean { public void sayHello() { System.out.println("Hello from MyBean!"); } } @ComponentScan class AppConfig {} public class MainApp { public static void main(String[] args) { // 创建Spring容器实例 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); // 获取Bean实例 MyBean myBean = context.getBean(MyBean.class); // 调用Bean方法 myBean.sayHello(); // 关闭容器 context.close(); } } ``` ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值