⭐⭐⭐ Spring Boot 项目实战 ⭐⭐⭐ Spring Cloud 项目实战
《Dubbo 实现原理与源码解析 —— 精品合集》 《Netty 实现原理与源码解析 —— 精品合集》
《Spring 实现原理与源码解析 —— 精品合集》 《MyBatis 实现原理与源码解析 —— 精品合集》
《Spring MVC 实现原理与源码解析 —— 精品合集》 《数据库实体设计合集》
《Spring Boot 实现原理与源码解析 —— 精品合集》 《Java 面试题 + Java 学习指南》

摘要: 原创出处 cnblogs.com/deng-cc/p/6373670.html 「Dulk」欢迎转载,保留摘要,谢谢!


🙂🙂🙂关注**微信公众号:【芋道源码】**有福利:

  1. RocketMQ / MyCAT / Sharding-JDBC 所有源码分析文章列表
  2. RocketMQ / MyCAT / Sharding-JDBC 中文注释源码 GitHub 地址
  3. 您对于源码的疑问每条留言将得到认真回复。甚至不知道如何读源码也可以请教噢
  4. 新的源码解析文章实时收到通知。每周更新一篇左右
  5. 认真的源码交流微信群。

ApplicationContextAware 接口的作用:

先来看下 Spring API 中对于 ApplicationContextAware 这个接口的描述:

图片

即是说,当一个类实现了这个接口之后,这个类就可以方便地获得 ApplicationContext 中的所有bean。

换句话说,就是这个类可以直接获取Spring配置文件中,所有有引用到的bean对象。

如何使用 ApplicationContextAware 接口?

如何使用该接口?很简单。

1、定义一个工具类,实现 ApplicationContextAware,实现 setApplicationContext方法

public class SpringContextUtils implements ApplicationContextAware {
private static ApplicationContext context;

@Override
public void setApplicationContext(ApplicationContext context)
throws BeansException {
SpringContextUtils.context = context;
}

public static ApplicationContext getContext(){
return context;
}

}

如此一来,我们就可以通过该工具类,来获得 ApplicationContext,进而使用其getBean方法来获取我们需要的bean。

2、在Spring配置文件中注册该工具类

之所以我们能如此方便地使用该工具类来获取,正是因为Spring能够为我们自动地执行 setApplicationContext 方法,显然,这也是因为IOC的缘故,所以必然这个工具类也是需要在Spring的配置文件中进行配置的。

<bean id="springContextUtils" class="com.zker.common.util.SpringContextUtils" />

3、编写方法进行使用

一切就绪,我们就可以在需要使用的地方调用该方法来获取bean了。

public String ajaxRegister() throws IOException {
UserDao userDao = (UserDao)SpringContextUtils.getContext().getBean("userDao");
if (userDao.findAdminByLoginName(loginName) != null
|| userDao.findUserByLoginName(loginName) != null) {
message.setMsg("用户名已存在");
message.setStatus(false);
} else {
message.setMsg("用户名可以注册");
message.setStatus(true);
}

return "register";
}

文章目录
  1. 1. ApplicationContextAware 接口的作用:
  2. 2. 1、定义一个工具类,实现 ApplicationContextAware,实现 setApplicationContext方法
  3. 3. 2、在Spring配置文件中注册该工具类
  4. 4. 3、编写方法进行使用