[英]NullPointerException while accessing an instance of Spring JdbcTemplate
[英]Getting nullpointerException while using the jdbcTemplate in spring
我是Spring的新手,正在开发我需要从数据库中获取一些数据的项目。 我正在使用tomcat服务器并使用JNDI DB连接池。 下面是我的代码和Spring配置。 我得到一个NullPointerException
因为jdbcTemplate
为null
。
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.