ApplicationContextAware 的理解和應用


  當我們在項目中獲取某一個spring bean時,可以定義一個類,實現ApplicationContextAware  該接口,該接口可以加載獲取到所有的 spring bean。

package com.lf.mp.test;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class ApplicationContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    /**
     * 實現ApplicationContextAware接口的回調方法,設置上下文環境
     *
     * @param applicationContext spring上下文對象
     * @throws BeansException 拋出spring異常
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextUtil.applicationContext = applicationContext;
    }

    /**
     * @return ApplicationContext
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 獲取對象
     *
     * @param name spring配置文件中配置的bean名或注解的名稱
     * @return 一個以所給名字注冊的bean的實例
     * @throws BeansException 拋出spring異常
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) throws BeansException {
        return (T) applicationContext.getBean(name);
    }

    /**
     * 獲取類型為requiredType的對象
     *
     * @param clazz 需要獲取的bean的類型
     * @return 該類型的一個在ioc容器中的bean
     * @throws BeansException 拋出spring異常
     */
    public static <T> T getBean(Class<T> clazz) throws BeansException {
        return applicationContext.getBean(clazz);
    }

    /**
     * 如果ioc容器中包含一個與所給名稱匹配的bean定義,則返回true否則返回false
     *
     * @param name ioc容器中注冊的bean名稱
     * @return 存在返回true否則返回false
     */
    public static boolean containsBean(String name) {
        return applicationContext.containsBean(name);
    }
}
ApplicationContextAware 接口的定義如下:
package org.springframework.context;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.Aware;

public interface ApplicationContextAware extends Aware {
    void setApplicationContext(ApplicationContext var1) throws BeansException;
}

通過實現 ApplicationContextAware 接口可以獲取所有的spring bean,是因為spring會自動執行setApplicationAware .

示例在類中獲取靜態bean的實例:

import com.alibaba.fastjson.JSONObject;
import com.lf.mp.entity.User;
import com.lf.mp.service.UserService;

public class SpringBeanTest {
    private static UserService userService;
    static {
        userService = ApplicationContextUtil.getBean(UserService.class);
    }
    public static void test(){
        User user = userService.getById(222L);
        System.out.println(JSONObject.toJSON(user));
    }
}

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM