2016-01-05 74 views
3

我是Spring的新手,正在從需要從數據庫獲取一些數據的項目上工作。我正在使用tomcat服務器並使用JNDI DB連接池。以下是我的代碼和Spring配置。我得到NullPointerException,因爲jdbcTemplatenull在Spring中使用jdbcTemplate時獲取nullpointerException

public class AppConfig 
{ 
@Autowired 
private JdbcTemplate jdbcTemplate; 
private static AppConfig config=null; 
private HashMap<String, String> dbAppParameterValuesCacheMap; 
public AppConfig() 
{ 
    cacheConfig(); 

} 

public boolean cacheConfig() 
{ 
    dbAppParameterValuesCacheMap = null; 
    List<Map<String, Object>> appConfigMapList=null; 
    String parameterType="PP_APP_CONFIG"; 
    try 
    { 
     appConfigMapList= jdbcTemplate 
      .queryForList("SELECT Parameter_Value, Parameter_Name FROM PP_Application_Parameter where PARAMETER_TYPE='"+parameterType+"'"); 
    } 
    catch(NullPointerException ex) 
    { 
     System.out.println("here"); 
     ex.printStackTrace(); 
    } 
    if (dbAppParameterValuesCacheMap == null) 
     dbAppParameterValuesCacheMap = new HashMap<String,String>(); 
    for(Map<String, Object> configMap:appConfigMapList) 
    { 
      dbAppParameterValuesCacheMap.put((String)configMap.get("Parameter_Name"), (String)configMap.get("Parameter_Value")); 
    } 

    return true; 
} 
} 

我的Spring配置文件中包含:

<bean id="dbDataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> 
    <property name="jndiName" value="java:comp/env/jdbc/PP_DATASOURCE" /> 
</bean> 
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" lazy-init="false"> 
    <property name="dataSource" ref="dbDataSource"></property> 
</bean> 
<bean id="config" class="AppConfig" scope="singleton"> 
</bean> 

JNDI已成功創建。我得到一個NullPointerException當它試圖執行行

appConfigMapList= jdbcTemplate 
      .queryForList("SELECT Parameter_Value, Parameter_Name FROM PP_Application_Parameter where PARAMETER_TYPE='"+parameterType+"'"); 
+0

堆棧跟蹤請。 – EJP

+0

您如何期待Spring將依賴注入到仍在構建的對象中? –

回答

1

爲每Autowired文件,注入建豆後會發生。

在調用任何配置方法之前,在構建bean之後立即注入字段。這樣的配置字段不一定是公開的。

由於你的代碼試圖從構造參考jdbcTemplate,但尚未注入,因此它是null

如果您的目標是在自動連線的依賴關係保證到位後運行一些額外的初始化代碼,那麼一種方法是使用PostContruct從構造函數中註釋不同的方法。

0

考慮這種變化:

public AppConfig() 
{ 
} 

@PostConstruct 
public boolean cacheConfig() 
{ 

這之後的autowirings已經被Spring同時保持你的語義(對象構造後立即運行cacheConfig)代替做移動到一個時間訪問的JdbcTemplate。

@Autowired字段在構造函數運行時爲空。

相關問題