簡體   English   中英

在spring中使用jdbcTemplate時獲取nullpointerException

[英]Getting nullpointerException while using the jdbcTemplate in spring

我是Spring的新手,正在開發我需要從數據庫中獲取一些數據的項目。 我正在使用tomcat服務器並使用JNDI DB連接池。 下面是我的代碼和Spring配置。 我得到一個NullPointerException因為jdbcTemplatenull

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+"'");

根據Autowired的文檔,在構建bean之后進行注入。

在調用任何配置方法之前,在構造bean之后立即注入字段。 這樣的配置字段不必是公共的。

由於您的代碼試圖從構造函數引用jdbcTemplate ,因此尚未注入,因此它為null

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

考慮這個變化:

public AppConfig()
{
}

@PostConstruct
public boolean cacheConfig()
{

這將把訪問jdbcTemplate的時間移到Spring完成自動連接之后的一段時間同時保持你的語義(在對象構建之后立即運行cacheConfig)。

@Autowired字段在構造函數運行時為null。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM