Spring ApplicationContextAware源码详解(详细注释版)
1. ApplicationContextAware接口源码
/*
* ApplicationContextAware接口是Spring框架中重要的Aware接口之一
* 允许Bean获取对其运行的ApplicationContext的引用
* 是Spring框架中依赖注入机制的重要组成部分
*
* ApplicationContextAware的作用:
* 1. 让Bean能够访问ApplicationContext
* 2. 实现Bean与Spring容器的交互
* 3. 获取容器中的其他Bean
* 4. 访问容器的各种服务
*
* 注意事项:
* - 实现此接口会将代码与Spring框架耦合
* - 优先考虑使用@Autowired注入ApplicationContext
* - 避免在业务逻辑中直接使用ApplicationContext
*/
package org.springframework.context;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.Aware;
/**
* 当Bean需要访问其运行的ApplicationContext时实现的接口
*
* 实现此接口的Bean会在ApplicationContextAwareProcessor处理时
* 调用setApplicationContext方法注入ApplicationContext引用
*
* 执行时机:
* Bean实例化 -> 属性注入 -> Aware接口方法调用(setApplicationContext) ->
* BeanPostProcessor前置处理 -> InitializingBean.afterPropertiesSet() ->
* 自定义init-method -> BeanPostProcessor后置处理 -> Bean可使用
*
* 使用场景:
* - 获取其他Bean实例
* - 访问容器的环境信息
* - 发布应用事件
* - 获取Bean定义信息
* - 访问消息源
*
* 注意:官方推荐使用@Autowired注入ApplicationContext而不是实现此接口
*/
public interface ApplicationContextAware extends Aware {
/**
* 设置此对象运行的ApplicationContext
* 在普通Bean属性填充之后但在初始化回调之前调用
* 如InitializingBean的afterPropertiesSet或自定义init-method
*
* @param applicationContext 此对象要使用的ApplicationContext对象
* @throws BeansException 如果ApplicationContext不能被设置
*
* 使用建议:
* - 在此方法中保存ApplicationContext引用
* - 避免在此方法中执行复杂的业务逻辑
* - 确保异常处理,避免影响Bean的正常创建
* - 考虑使用@Autowired替代实现此接口
*/
void setApplicationContext(ApplicationContext applicationContext) throws BeansException;
}
2. Aware接口体系
/*
* Aware接口是Spring框架中所有感知接口的根接口
* 标记接口,没有任何方法
*/
package org.springframework.beans.factory;
/**
* 标记超接口,指示Bean有资格通过回调方式由Spring容器通知
* 实际的方法由子接口定义,通常表示为set方法
*
* Aware接口的设计目的是为了让Bean能够感知到容器的存在
* 并获取容器提供的各种服务
*
* 常见的Aware接口:
* - BeanNameAware: 获取Bean名称
* - BeanFactoryAware: 获取BeanFactory
* - ApplicationContextAware: 获取ApplicationContext
* - EnvironmentAware: 获取Environment
* - EmbeddedValueResolverAware: 获取StringValueResolver
* - ResourceLoaderAware: 获取ResourceLoader
* - ApplicationEventPublisherAware: 获取ApplicationEventPublisher
* - MessageSourceAware: 获取MessageSource
*/
public interface Aware {
}
3. ApplicationContextAwareProcessor处理器
/*
* ApplicationContextAwareProcessor是处理各种Aware接口的BeanPostProcessor
* 负责在Bean初始化过程中调用相应的Aware接口方法
*/
package org.springframework.context.support;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.*;
class ApplicationContextAwareProcessor implements BeanPostProcessor {
private final ConfigurableApplicationContext applicationContext;
/**
* 构造方法
*
* @param applicationContext ApplicationContext实例
*/
public ApplicationContextAwareProcessor(ConfigurableApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
/**
* 在Bean初始化前处理Aware接口
* 这是ApplicationContextAware被调用的地方
*
* @param bean Bean实例
* @param beanName Bean名称
* @return 处理后的Bean实例
* @throws BeansException 如果处理过程中发生错误
*/
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
// 检查Bean是否实现了任何Aware接口
if (!(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)){
return bean;
}
AccessControlContext acc = null;
// 如果有安全管理器,获取访问控制上下文
if (System.getSecurityManager() != null) {
acc = this.applicationContext.getBeanFactory().getAccessControlContext();
}
if (acc != null) {
// 在安全管理器下执行Aware接口方法
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareInterfaces(bean);
return null;
}, acc);
}
else {
// 直接执行Aware接口方法
invokeAwareInterfaces(bean);
}
return bean;
}
/**
* 调用各种Aware接口方法
* 按照特定顺序调用,确保依赖关系正确
*
* @param bean Bean实例
*/
private void invokeAwareInterfaces(Object bean) {
// EnvironmentAware接口
if (bean instanceof EnvironmentAware) {
((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
}
// EmbeddedValueResolverAware接口
if (bean instanceof EmbeddedValueResolverAware) {
((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(
new EmbeddedValueResolver(this.applicationContext.getBeanFactory()));
}
// ResourceLoaderAware接口
if (bean instanceof ResourceLoaderAware) {
((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
}
// ApplicationEventPublisherAware接口
if (bean instanceof ApplicationEventPublisherAware) {
((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
}
// MessageSourceAware接口
if (bean instanceof MessageSourceAware) {
((MessageSourceAware) bean).setMessageSource(this.applicationContext);
}
// ApplicationContextAware接口 - 这里是关键调用点
if (bean instanceof ApplicationContextAware) {
((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
}
}
/**
* 嵌入值解析器
* 用于解析占位符等嵌入值
*/
private static class EmbeddedValueResolver implements StringValueResolver {
private final ConfigurableBeanFactory beanFactory;
public EmbeddedValueResolver(ConfigurableBeanFactory beanFactory) {
this.beanFactory = beanFactory;
}
@Override
public String resolveStringValue(String strVal) {
return this.beanFactory.resolveEmbeddedValue(strVal);
}
}
}
4. AbstractAutowireCapableBeanFactory中Aware接口处理
/*
* AbstractAutowireCapableBeanFactory中Aware接口的处理逻辑
*/
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
implements AutowireCapableBeanFactory {
/**
* 调用Aware接口相关方法
* 在Bean初始化过程中调用
*
* @param beanName Bean名称
* @param bean Bean实例
*/
private void invokeAwareMethods(final String beanName, final Object bean) {
if (bean instanceof Aware) {
// BeanNameAware接口
if (bean instanceof BeanNameAware) {
((BeanNameAware) bean).setBeanName(beanName);
}
// BeanClassLoaderAware接口
if (bean instanceof BeanClassLoaderAware) {
ClassLoader bcl = getBeanClassLoader();
if (bcl != null) {
((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
}
}
// BeanFactoryAware接口
if (bean instanceof BeanFactoryAware) {
((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
}
}
}
/**
* 初始化Bean的核心方法
* 包含Aware接口方法的调用
*
* @param beanName Bean名称
* @param bean Bean实例
* @param mbd 合并的Bean定义
* @return 初始化完成的Bean实例
*/
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
}
else {
// 调用Aware接口方法
invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
// 应用BeanPostProcessor的前置处理(包括ApplicationContextAwareProcessor)
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
// 调用初始化方法
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
throw new BeanCreationException(
(mbd != null ? mbd.getResourceDescription() : null),
beanName, "Invocation of init method failed", ex);
}
if (mbd == null || !mbd.isSynthetic()) {
// 应用BeanPostProcessor的后置处理
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
}
5. ApplicationContextAware的实际应用
/*
* ApplicationContextAware的实际应用场景
*/
/**
* 服务定位器模式实现
* 通过ApplicationContext获取其他Bean
*/
@Component
public class ServiceLocator implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ServiceLocator.applicationContext = applicationContext;
}
/**
* 获取Bean实例
*
* @param beanClass Bean类型
* @param <T> Bean类型泛型
* @return Bean实例
*/
public static <T> T getBean(Class<T> beanClass) {
return applicationContext.getBean(beanClass);
}
/**
* 根据名称获取Bean实例
*
* @param beanName Bean名称
* @param <T> Bean类型泛型
* @return Bean实例
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String beanName) {
return (T) applicationContext.getBean(beanName);
}
/**
* 检查Bean是否存在
*
* @param beanName Bean名称
* @return 如果存在返回true
*/
public static boolean containsBean(String beanName) {
return applicationContext.containsBean(beanName);
}
}
/**
* 应用事件发布器
* 使用ApplicationContext发布事件
*/
@Component
public class EventPublisher implements ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
/**
* 发布自定义事件
*
* @param event 事件对象
*/
public void publishEvent(ApplicationEvent event) {
applicationContext.publishEvent(event);
}
/**
* 发布对象事件
*
* @param event 事件对象
*/
public void publishEvent(Object event) {
applicationContext.publishEvent(event);
}
}
/**
* 配置信息服务
* 访问应用配置信息
*/
@Component
public class ConfigService implements ApplicationContextAware {
private ApplicationContext applicationContext;
private Environment environment;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
this.environment = applicationContext.getEnvironment();
}
/**
* 获取配置属性
*
* @param key 属性键
* @return 属性值
*/
public String getProperty(String key) {
return environment.getProperty(key);
}
/**
* 获取配置属性,带默认值
*
* @param key 属性键
* @param defaultValue 默认值
* @return 属性值
*/
public String getProperty(String key, String defaultValue) {
return environment.getProperty(key, defaultValue);
}
/**
* 获取Bean定义名称数组
*
* @return Bean定义名称数组
*/
public String[] getBeanDefinitionNames() {
if (applicationContext instanceof ConfigurableApplicationContext) {
ConfigurableListableBeanFactory beanFactory =
((ConfigurableApplicationContext) applicationContext).getBeanFactory();
return beanFactory.getBeanDefinitionNames();
}
return new String[0];
}
/**
* 获取Bean定义数量
*
* @return Bean定义数量
*/
public int getBeanDefinitionCount() {
if (applicationContext instanceof ConfigurableApplicationContext) {
ConfigurableListableBeanFactory beanFactory =
((ConfigurableApplicationContext) applicationContext).getBeanFactory();
return beanFactory.getBeanDefinitionCount();
}
return 0;
}
}
/**
* 国际化消息服务
* 使用MessageSource获取国际化消息
*/
@Component
public class MessageService implements ApplicationContextAware {
private MessageSource messageSource;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.messageSource = applicationContext;
}
/**
* 获取国际化消息
*
* @param code 消息代码
* @param locale 本地化
* @return 消息文本
*/
public String getMessage(String code, Locale locale) {
return messageSource.getMessage(code, null, locale);
}
/**
* 获取国际化消息,带参数
*
* @param code 消息代码
* @param args 消息参数
* @param locale 本地化
* @return 消息文本
*/
public String getMessage(String code, Object[] args, Locale locale) {
return messageSource.getMessage(code, args, locale);
}
/**
* 获取国际化消息,带默认值
*
* @param code 消息代码
* @param args 消息参数
* @param defaultMessage 默认消息
* @param locale 本地化
* @return 消息文本
*/
public String getMessage(String code, Object[] args, String defaultMessage, Locale locale) {
return messageSource.getMessage(code, args, defaultMessage, locale);
}
}
/**
* 资源加载服务
* 使用ResourceLoader加载资源
*/
@Component
public class ResourceService implements ApplicationContextAware {
private ResourceLoader resourceLoader;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.resourceLoader = applicationContext;
}
/**
* 获取资源
*
* @param location 资源位置
* @return 资源对象
*/
public Resource getResource(String location) {
return resourceLoader.getResource(location);
}
/**
* 获取类加载器
*
* @return 类加载器
*/
public ClassLoader getClassLoader() {
return resourceLoader.getClassLoader();
}
}
6. 现代化替代方案
/*
* 现代化的替代方案
* 推荐使用依赖注入而不是实现Aware接口
*/
/**
* 使用@Autowired注入ApplicationContext
* 推荐的现代化方式
*/
@Component
public class ModernService {
// 使用@Autowired注入ApplicationContext
@Autowired
private ApplicationContext applicationContext;
// 使用@Autowired注入Environment
@Autowired
private Environment environment;
// 使用@Autowired注入其他Bean
@Autowired
private SomeOtherService someOtherService;
/**
* 获取Bean实例
*/
public void doSomething() {
// 直接使用注入的ApplicationContext
SomeService someService = applicationContext.getBean(SomeService.class);
// 使用注入的Environment
String propertyValue = environment.getProperty("some.property");
// 直接使用注入的其他Bean
someOtherService.performAction();
}
}
/**
* 使用构造方法注入
* 更好的依赖注入方式
*/
@Component
public class ConstructorInjectionService {
private final ApplicationContext applicationContext;
private final Environment environment;
private final SomeOtherService someOtherService;
// 构造方法注入
public ConstructorInjectionService(
ApplicationContext applicationContext,
Environment environment,
SomeOtherService someOtherService) {
this.applicationContext = applicationContext;
this.environment = environment;
this.someOtherService = someOtherService;
}
/**
* 业务方法
*/
public void doSomething() {
// 使用注入的依赖
SomeService someService = applicationContext.getBean(SomeService.class);
String propertyValue = environment.getProperty("some.property");
someOtherService.performAction();
}
}
/**
* 使用@Value注解注入配置属性
* 替代Environment的使用
*/
@Component
public class PropertyValueService {
// 直接注入配置属性
@Value("${app.name:defaultAppName}")
private String appName;
@Value("${app.version:1.0.0}")
private String appVersion;
@Value("${database.url:jdbc:h2:mem:testdb}")
private String databaseUrl;
/**
* 获取应用名称
*/
public String getAppName() {
return appName;
}
/**
* 获取应用版本
*/
public String getAppVersion() {
return appVersion;
}
}
/**
* 使用事件监听器替代手动事件发布
*/
@Component
public class EventListenerService {
// 监听自定义事件
@EventListener
public void handleCustomEvent(CustomEvent event) {
System.out.println("处理自定义事件: " + event.getMessage());
}
// 监听上下文刷新事件
@EventListener
public void handleContextRefresh(ContextRefreshedEvent event) {
System.out.println("应用上下文已刷新");
}
// 监听上下文关闭事件
@EventListener
public void handleContextClosed(ContextClosedEvent event) {
System.out.println("应用上下文已关闭");
}
}
/**
* 自定义事件类
*/
public class CustomEvent extends ApplicationEvent {
private final String message;
public CustomEvent(Object source, String message) {
super(source);
this.message = message;
}
public String getMessage() {
return message;
}
}
7. 实际使用示例
/*
* ApplicationContextAware实际使用示例
*/
/**
* 动态Bean查找服务
*/
@Component
public class DynamicBeanLookupService implements ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
/**
* 根据类型查找Bean
*/
public <T> List<T> findBeansOfType(Class<T> type) {
Map<String, T> beans = applicationContext.getBeansOfType(type);
return new ArrayList<>(beans.values());
}
/**
* 根据注解查找Bean
*/
public List<Object> findBeansWithAnnotation(Class<? extends Annotation> annotationType) {
List<Object> beans = new ArrayList<>();
String[] beanNames = applicationContext.getBeanDefinitionNames();
for (String beanName : beanNames) {
Class<?> beanType = applicationContext.getType(beanName);
if (beanType != null && beanType.isAnnotationPresent(annotationType)) {
beans.add(applicationContext.getBean(beanName));
}
}
return beans;
}
/**
* 动态获取Bean
*/
@SuppressWarnings("unchecked")
public <T> T getBeanDynamically(String beanName, Class<T> requiredType) {
try {
return (T) applicationContext.getBean(beanName);
} catch (BeansException e) {
// 处理Bean不存在的情况
System.err.println("Bean '" + beanName + "' not found: " + e.getMessage());
return null;
}
}
}
/**
* 应用监控服务
*/
@Component
public class ApplicationMonitorService implements ApplicationContextAware {
private ApplicationContext applicationContext;
private final Logger logger = LoggerFactory.getLogger(ApplicationMonitorService.class);
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
/**
* 获取应用统计信息
*/
public ApplicationStats getApplicationStats() {
ApplicationStats stats = new ApplicationStats();
// 获取Bean数量
if (applicationContext instanceof ConfigurableApplicationContext) {
ConfigurableListableBeanFactory beanFactory =
((ConfigurableApplicationContext) applicationContext).getBeanFactory();
stats.setBeanCount(beanFactory.getBeanDefinitionCount());
}
// 获取启动时间
if (applicationContext instanceof ConfigurableApplicationContext) {
long startupDate = ((ConfigurableApplicationContext) applicationContext).getStartupDate();
stats.setStartupTime(new Date(startupDate));
}
// 获取环境信息
Environment environment = applicationContext.getEnvironment();
stats.setActiveProfiles(Arrays.asList(environment.getActiveProfiles()));
// 获取Bean名称列表
stats.setBeanNames(Arrays.asList(applicationContext.getBeanDefinitionNames()));
return stats;
}
/**
* 监控Bean创建
*/
public void monitorBeanCreation() {
applicationContext.addApplicationListener(new ApplicationListener<ContextRefreshedEvent>() {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
logger.info("应用上下文刷新完成,共创建 {} 个Bean",
applicationContext.getBeanDefinitionCount());
}
});
}
/**
* 应用统计信息类
*/
public static class ApplicationStats {
private int beanCount;
private Date startupTime;
private List<String> activeProfiles;
private List<String> beanNames;
// Getters and Setters
public int getBeanCount() { return beanCount; }
public void setBeanCount(int beanCount) { this.beanCount = beanCount; }
public Date getStartupTime() { return startupTime; }
public void setStartupTime(Date startupTime) { this.startupTime = startupTime; }
public List<String> getActiveProfiles() { return activeProfiles; }
public void setActiveProfiles(List<String> activeProfiles) { this.activeProfiles = activeProfiles; }
public List<String> getBeanNames() { return beanNames; }
public void setBeanNames(List<String> beanNames) { this.beanNames = beanNames; }
}
}
/**
* 配置热加载服务
*/
@Component
public class ConfigurationReloadService implements ApplicationContextAware, DisposableBean {
private ApplicationContext applicationContext;
private ScheduledExecutorService scheduler;
private final Map<String, String> lastKnownConfig = new ConcurrentHashMap<>();
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
initializeScheduler();
}
/**
* 初始化调度器
*/
private void initializeScheduler() {
scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(this::checkConfigurationChanges, 30, 30, TimeUnit.SECONDS);
}
/**
* 检查配置变化
*/
private void checkConfigurationChanges() {
Environment environment = applicationContext.getEnvironment();
String[] propertyNames = {"app.name", "app.version", "database.url"}; // 示例属性
for (String propertyName : propertyNames) {
String currentValue = environment.getProperty(propertyName);
String lastValue = lastKnownConfig.get(propertyName);
if (currentValue != null && !currentValue.equals(lastValue)) {
logger.info("配置项 '{}' 发生变化: {} -> {}",
propertyName, lastValue, currentValue);
lastKnownConfig.put(propertyName, currentValue);
// 发布配置变化事件
applicationContext.publishEvent(
new ConfigurationChangeEvent(this, propertyName, lastValue, currentValue));
}
}
}
@Override
public void destroy() throws Exception {
if (scheduler != null) {
scheduler.shutdown();
try {
if (!scheduler.awaitTermination(30, TimeUnit.SECONDS)) {
scheduler.shutdownNow();
}
} catch (InterruptedException e) {
scheduler.shutdownNow();
Thread.currentThread().interrupt();
}
}
}
/**
* 配置变化事件
*/
public static class ConfigurationChangeEvent extends ApplicationEvent {
private final String propertyName;
private final String oldValue;
private final String newValue;
public ConfigurationChangeEvent(Object source, String propertyName,
String oldValue, String newValue) {
super(source);
this.propertyName = propertyName;
this.oldValue = oldValue;
this.newValue = newValue;
}
// Getters
public String getPropertyName() { return propertyName; }
public String getOldValue() { return oldValue; }
public String getNewValue() { return newValue; }
}
}
8. 最佳实践和注意事项
/*
* ApplicationContextAware最佳实践
*/
/**
* 正确的实现方式
*/
@Component
public class GoodExampleService implements ApplicationContextAware {
private ApplicationContext applicationContext;
private Environment environment;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
// 保存引用
this.applicationContext = applicationContext;
this.environment = applicationContext.getEnvironment();
// 记录日志
logger.info("ApplicationContext已注入到 {}", this.getClass().getSimpleName());
}
/**
* 安全地获取Bean
*/
public <T> Optional<T> getBeanSafely(Class<T> beanClass) {
try {
return Optional.of(applicationContext.getBean(beanClass));
} catch (BeansException e) {
logger.warn("无法获取Bean {}: {}", beanClass.getSimpleName(), e.getMessage());
return Optional.empty();
}
}
/**
* 检查Bean是否存在
*/
public boolean isBeanExists(String beanName) {
return applicationContext.containsBean(beanName);
}
}
/**
* 避免的错误实现
*/
@Component
public class BadExampleService implements ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
// 错误1: 在Aware方法中执行复杂业务逻辑
performComplexBusinessLogic(); // 应该避免
// 错误2: 不处理异常
Object someBean = applicationContext.getBean("nonExistentBean"); // 可能抛出异常
// 错误3: 在Aware方法中发布事件
applicationContext.publishEvent(new CustomEvent(this, "初始化完成")); // 不推荐
}
private void performComplexBusinessLogic() {
// 复杂的业务逻辑不应该在这里执行
}
}
/**
* 现代化替代方案
*/
@Component
public class ModernAlternativeService {
// 推荐使用依赖注入
@Autowired
private ApplicationContext applicationContext;
@Autowired
private Environment environment;
// 使用@PostConstruct进行初始化
@PostConstruct
public void initialize() {
logger.info("服务初始化完成");
// 可以在这里执行初始化逻辑
}
// 使用@PreDestroy进行清理
@PreDestroy
public void cleanup() {
logger.info("服务清理完成");
// 可以在这里执行清理逻辑
}
}
/**
* 线程安全的实现
*/
@Component
public class ThreadSafeService implements ApplicationContextAware {
private volatile ApplicationContext applicationContext;
private final Object lock = new Object();
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
synchronized (lock) {
this.applicationContext = applicationContext;
}
}
/**
* 线程安全地获取Bean
*/
public <T> T getBean(Class<T> beanClass) {
ApplicationContext context = this.applicationContext;
if (context == null) {
throw new IllegalStateException("ApplicationContext尚未注入");
}
return context.getBean(beanClass);
}
}
9. 核心设计要点总结
9.1 设计目的
- 提供Bean访问ApplicationContext的途径
- 实现Bean与Spring容器的交互
- 支持动态Bean查找和服务获取
9.2 调用时机
- Bean实例化完成
- 属性注入完成
- setApplicationContext方法调用
- 其他Aware接口方法调用
- BeanPostProcessor处理
- InitializingBean.afterPropertiesSet()
9.3 使用建议
- 优先使用@Autowired注入:减少与Spring框架的耦合
- 谨慎使用:避免在业务逻辑中直接使用ApplicationContext
- 异常处理:适当处理可能发生的BeansException
- 性能考虑:避免频繁的Bean查找操作
9.4 替代方案
- @Autowired注入ApplicationContext
- 构造方法注入
- @Value注入配置属性
- @EventListener处理事件
- @PostConstruct和@PreDestroy处理生命周期
9.5 常见应用场景
- 动态Bean查找
- 配置属性访问
- 应用事件发布
- 资源加载
- 国际化消息获取
- 应用监控和管理
9.6 最佳实践
- 实现幂等性,确保可以安全地多次调用
- 适当的异常处理和日志记录
- 避免在Aware方法中执行复杂业务逻辑
- 考虑线程安全性
- 使用现代化的依赖注入方式
ApplicationContextAware作为Spring框架的重要组成部分,为开发者提供了访问容器功能的途径,但应该谨慎使用并优先考虑现代化的替代方案。

6736

被折叠的 条评论
为什么被折叠?



