Spring @Autowired注入爲null,空指針異常

Spring @Autowired註冊爲空,最常見的原因是查看自動注入的服務是否被註冊爲Bean,由容器來管理。

還有一個原因稍微隱晦一點,就是自動注入的服務的對象是new 來的,而不是通過Spring容器來管理。

比如:

1.先定義一個服務

@Service("xxxService")

public class Xxxmpl implements Ixxx{

@Override

public void doSomething(){

//

}

}

2.調用服務

public class BClazz{

@Autowired

private Ixxx xxxService;

public void doSomething(){

}

}

3、如果BClass 的示例是 通過 new BClazz()來的,那麼會注入失敗,xxxService爲null.

解決辦法就是在使用到服務的時候,動態去加載Bean,常用的是實現ApplicationContextAware接口方式,代碼如下:


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

public class SpringContextUtil implements ApplicationContextAware{
//     Spring應用上下文環境  
    private static ApplicationContext applicationContext;  
  
    /** 
     * 實現ApplicationContextAware接口的回調方法,設置上下文環境 
     *  
     * @param applicationContext 
     */  
    public void setApplicationContext(ApplicationContext applicationContext) {  
        SpringContextUtil.applicationContext = applicationContext;  
    }  
  
    /** 
     * @return ApplicationContext 
     */  
    public static ApplicationContext getApplicationContext() {  
        return applicationContext;  
    }  
  
    /** 
     * 獲取對象 
     * 這裏重寫了bean方法,起主要作用 
     * @param name 
     * @return Object 一個以所給名字註冊的bean的實例 
     * @throws BeansException 
     */  
    public static Object getBean(String name) throws BeansException {  
        return applicationContext.getBean(name);  
    }  
    public static <T> T getBean(Class<T> requiredType) {
         
        return applicationContext.getBean(requiredType);
    }

}
 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章