Spring Aware接口
文章目录
容器管理的 Bean 一般不需要了解容器的状态和直接使用容器, 但是在某些情况下, 是需要在 Bean 中直接对IOC容器进行操作的, 可以通过特定的 Aware 接口来完成. aware 接口有以下这些:
| 接口名 | 描述 |
|---|---|
| ApplicationContextAware | 实现了这个接口的类都可以获取到一个 ApplicationContext 对象. 可以获取容器中的所有 Bean |
| ApplicationEventPublisherAware | 在 bean 中可以得到应用上下文的事件发布器, 从而可以在Bean中发布应用上下文的事件. |
| BeanClassLoaderAware | 获取 bean 的类加载器 |
| BeanFactoryAware | 获取 bean 的工厂 |
| BeanNameAware | 获取 bean 在容器中的名字 |
| BootstrapContextAware | 获取 BootstrapContext |
| LoadTimeWeaverAware | 加载Spring Bean时织入第三方模块, 如AspectJ |
| MessageSourceAware | 主要用于获取国际化相关接口 |
| NotificationPublisherAware | 用于获取通知发布者 |
| ResourceLoaderAware | 初始化时注入ResourceLoader |
| ServletConfigAware | web开发过程中获取ServletConfig |
| ServletContextAware | web开发过程中获取ServletContext信息 |
ApplicationContextAware 接口
这个接口比较常用, ApplicationContextAware 接口中只有一个方法, 用来获取容器中的所有 Bean.
void setApplicationContext(ApplicationContext applicationContext) throws BeansException;
@Component
public class Test implements ApplicationContextAware {
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
}
}
这里提供一个常用的工具类
@Component
public class SpringUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(
ApplicationContext applicationContext) throws BeansException {
SpringUtil.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 根据Bean名称获取实例
*
* @param name
*
* Bean注册名称
* @return bean实例
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(
String name) throws BeansException {
return (T) applicationContext.getBean(name);
}
}
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论