新建网站怎么做优化/百度指数可以查询多长时间的
ApplicationContextAware 接口的作用
先来看下Spring API 中对于 ApplicationContextAware 这个接口的描述:
即是说,当一个类实现了这个接口之后,这个类就可以方便地获得 ApplicationContext 中的所有bean。换句话说,就是这个类可以直接获取Spring配置文件中,所有有引用到的bean对象。
如何使用 ApplicationContextAware 接口
如何使用该接口?很简单。
1、定义一个工具类,实现 ApplicationContextAware,实现 setApplicationContext方法
public class SpringContextUtils implements ApplicationContextAware { private static ApplicationContext context;@Overridepublic void setApplicationContext(ApplicationContext context)throws BeansException {SpringContextUtils.context = context;}public static ApplicationContext getContext(){return context;}}
如此一来,我们就可以通过该工具类,来获得 ApplicationContext,进而使用其getBean方法来获取我们需要的bean。
2、在Spring配置文件中注册该工具类
之所以我们能如此方便地使用该工具类来获取,正是因为Spring能够为我们自动地执行 setApplicationContext 方法,显然,这也是因为IOC的缘故,所以必然这个工具类也是需要在Spring的配置文件中进行配置的。
<!--Spring中bean获取的工具类-->
<bean id="springContextUtils" class="com.zker.common.util.SpringContextUtils" />
3、编写方法进行使用
一切就绪,我们就可以在需要使用的地方调用该方法来获取bean了。
/*** 利用Ajax实现注册的用户名重复性校验* @return*/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";}
转载:https://www.cnblogs.com/deng-cc/p/6373670.html