我在以下代码中不断通过 Spring 注入数据源获得 NPE。
我上了两节课。超类
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();
}
}
}
这是从中注入 DataSource 的 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>
我一直在 main 方法的最后一行获取 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();}
需要进入名为say的主类的方法,initResourceSource()
所以我必须将appContext传递给该方法,因此getBean()
没有解决方案