我一直在用以下代码注入数据源的Spring中创建NPE。Spring 3:数据源注入和NullPointerException
我有两个班。 Superclasss
public class RepositorySource extends PropertiesConfiguration{
private RepositoryView repositoryView;
public RepositoryView getRepositoryView() {
return repositoryView;
}
public void setRepositoryView(RepositoryView repositoryView) {
this.repositoryView = repositoryView;
}
}
和子
public class RepositoryView {
private DataSource dataSource;
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public void testConn_RV(
Connection con;
try {
con = dataSource.getConnection();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
这里是bean定义从中注入数据源:
<bean id="RepositorySourceBean" class="com.acme.persistence.metamodel.views.impl.RepositorySource" >
<property name="repositoryView">
<bean class="com.acme.persistence.metamodel.views.impl.RepositoryView">
<property name="dataSource" ref="mysqlDataSource"> </property>
</bean>
</property>
</bean>
与数据源bean:
<!-- DATABASE PROPERTIES LOCALIZATION -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>properties/mysql-persistence.properties</value>
</property>
</bean>
<!-- DATASOURCE DEFINITION -->
<bean id="mysqlDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
我一直获得NPE主要方法的最后一行:
public static void main(String[] args)
{
App app = new App();
ApplicationContext appContext =
new ClassPathXmlApplicationContext("spring/configBeans/BeanLocations.xml");
RepositorySource src = new RepositorySource();
src.getRepositoryView().testConn_RV();} //<----- NPE HERE
看来DataSource不是初始化的,但为什么?
如何解决这个问题?
编辑 这一部分:
RepositorySource src = new RepositorySource();
src.getRepositoryView().testConn_RV();}
需要去被称为主类的方法说initResourceSource()
,所以我将不得不appContext传递给方法,以便因此getBean()
没有解决
您还没有任何注射注入这一点。 –
如果你的意思是getBean,那么getBean()不是DI。 [这是为什么](http://stackoverflow.com/questions/812415/why-is-springs-applicationcontext-getbean-considered-bad) – mCs