獲取Spring容器Bean對象工具類


        在開發中,總是能碰到用注解注入不了Spring容器里面bean對象的問題。為了解決這個問題,我們需要一個工具類來直接獲取Spring容器中的bean。因此就寫了這個工具類,在此記錄一下,方便后續查閱。廢話不多說,直接上代碼。

一、代碼

package com.zxy.demo.spring;

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

/**
 * 獲取Spring容器中bean工具類
 * @author ZENG.XIAO.YAN
 * @date   2018年6月6日
 * 
 */
@Component("springContextUtils")
public class SpringContextUtils implements ApplicationContextAware {

	private static ApplicationContext applicationContext = null;

	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	@SuppressWarnings("unchecked")
	public static <T> T getBean(String beanId) {
		return (T) applicationContext.getBean(beanId);
	}

	public static <T> T getBean(Class<T> requiredType) {
		return (T) applicationContext.getBean(requiredType);
	}

	/**
	 * Spring容器啟動后,會把 applicationContext 給自動注入進來,然后我們把 applicationContext 賦值到靜態變量中,方便后續拿到容器對象
	 * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)
	 */
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		SpringContextUtils.applicationContext = applicationContext;
	}

}

二、用法

        直接在代碼用調用 SpringContextUtils 靜態方法獲取bean就ok,可以通過bean的id獲取,也可以通過bean的類型獲取
RedisUtil redisUtil = SpringContextUtils.getBean(RedisUtil.class);

三、注意事項

        仔細看代碼可以發現我這個工具類上面加了個 @Component 注解。加這個注解的目的是為了把的 SpringContextUtils 的實例化交給Spring容器管理。當然,你也可以在xml中配置這個,我為了方便,直接用的注解。注意點:這個工具類的實例化必須由Spring容器來做


免責聲明!

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



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