使用SpringContextHolder獲取bean實例


1,介紹與使用
SpringContextHolder工具類的方法getBean可以獲取bean的實例。但是工具類的方法是不是static的,等同於@Autowired 注入。

解決問題:

類中方法是static,方法中使用的對象也必須是static,但正常情況下@Autowired無法注入靜態的bean,於是發現項目中用到了springContextHolder,通過使用;

UserService userService = SpringContextHolder.getBean(UserService.class);   // 獲取bean

 

2.異常  

使用SpringContextHolder來獲取一個bean報異常:

Java.lang.IllegalStateException: applicaitonContext屬性未注入, 請在applicationContext.xml中定義SpringContextHolder.
    at org.apache.commons.lang3.Validate.validState(Validate.java:826)
    at com.jituan.common.util.SpringContextHolder.assertContextInjected(SpringContextHolder.java:79)
    at com.jituan.common.util.SpringContextHolder.getBean(SpringContextHolder.java:41)
    at com.jituan.common.message.util.sms.SmsUtil.querySmsTemplate(SmsUtil.java:206)
    at com.jituan.common.message.util.sms.SmsUtil.send(SmsUtil.java:76)
    at com.jituan.common.message.processer.SmsProcesser.send(SmsProcesser.java:37)
    at com.jituan.batch.msghandler.MessageHandler.smsSend(MessageHandler.java:106)
    at com.jituan.batch.msghandler.MessageHandler$SmsTread.run(MessageHandler.java:185)

1)配置spring-mvc.xml

<!-- 設全局變量以便可以獲得對應的注入bean -->
<bean id="springContextHolder" class="com.jituan.common.util.SpringContextHolder" />

2)在SpringContextHolder類上加入注解@Service、@Lazy(false)

import java.util.Map;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
 
/**
 *
 *以靜態變量保存Spring ApplicationContext, 可在任何代碼任何地方任何時候中取出ApplicaitonContext.
 * @author Bucky
 */
@Service
@Lazy(false)
public class SpringContextHolder implements ApplicationContextAware{
 
    private static ApplicationContext applicationContext;
 
     
    //實現ApplicationContextAware接口的context注入函數, 將其存入靜態變量.
    public void setApplicationContext(ApplicationContext applicationContext) {
        SpringContextHolder.applicationContext = applicationContext;
    }
 
    
    //取得存儲在靜態變量中的ApplicationContext.
    public static ApplicationContext getApplicationContext() {
        checkApplicationContext();
        return applicationContext;
    }
     
    //從靜態變量ApplicationContext中取得Bean, 自動轉型為所賦值對象的類型.
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        checkApplicationContext();
        return (T) applicationContext.getBean(name);
    }
 
     
    //從靜態變量ApplicationContext中取得Bean, 自動轉型為所賦值對象的類型.
    //如果有多個Bean符合Class, 取出第一個.
    @SuppressWarnings("unchecked")
    public static <T> T getBean(Class<T> clazz) {
        checkApplicationContext();
        @SuppressWarnings("rawtypes")
                Map beanMaps = applicationContext.getBeansOfType(clazz);
        if (beanMaps!=null && !beanMaps.isEmpty()) {
            return (T) beanMaps.values().iterator().next();
        } else{
            return null;
        }
    }
 
    private static void checkApplicationContext() {
        if (applicationContext == null) {
            throw new IllegalStateException("applicaitonContext未注入,請在applicationContext.xml中定義SpringContextHolder");
        }
    }
 
}

  

 


免責聲明!

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



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