如何手動獲取Spring容器中的bean(ApplicationContextAware 接口)

ApplicationContextAware 接口的做用

先來看下Spring API 中對於 ApplicationContextAware 這個接口的描述:

 
便是說,當一個類實現了這個接口以後,這個類就能夠方便地得到 ApplicationContext 中的全部bean。換句話說,就是這個類能夠直接獲取Spring配置文件中,全部有引用到的bean對象。


如何使用 ApplicationContextAware 接口

如何使用該接口?很簡單。

一、定義一個工具類,實現 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。

二、在Spring配置文件中註冊該工具類

之因此咱們能如此方便地使用該工具類來獲取,正是由於Spring可以爲咱們自動地執行 setApplicationContext 方法,顯然,這也是由於IOC的緣故,因此必然這個工具類也是須要在Spring的配置文件中進行配置的。
<!--Spring中bean獲取的工具類-->
<bean id="springContextUtils" class="com.zker.common.util.SpringContextUtils" />

三、編寫方法進行使用

一切就緒,咱們就能夠在須要使用的地方調用該方法來獲取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";
    }


參考連接

相關文章
相關標籤/搜索