在使用Spring的jdbcTemplate时出现了nullpointerException错误

3

我刚接触Spring,正在处理需要从数据库获取数据的项目。我正在使用tomcat服务器和使用JNDI DB连接池。以下是我的代码和Spring配置。由于jdbcTemplatenull而导致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+"'");

你如何期望Spring将依赖注入到仍在构建中的对象中? - M. Deinum
2个回答

1
根据Autowired的文档,注入发生在bean构造之后。

字段在bean构造之后立即注入,在调用任何配置方法之前。这样的配置字段不必是公共的。

由于您的代码尝试从构造函数引用jdbcTemplate,因此它尚未被注入,因此它为null
如果您的目标是在自动连线依赖项已经准备就绪后运行一些额外的初始化代码,则可以使用PostContruct注释不同的方法而不是构造函数。

0

考虑这个变化:

public AppConfig()
{
}

@PostConstruct
public boolean cacheConfig()
{

这将把访问jdbcTemplate的时间推迟到Spring完成自动装配之后,同时保持您的语义(在对象构造之后立即运行cacheConfig)。

@Autowired字段在构造函数运行时为null。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接