2015-07-22 207 views
1

我正在嘗試使用spring框架對mysql數據庫執行一些crud操作。 我加了Maven的依賴關係,這是我的datasource.xml:Spring + JDBC無法連接到數據庫

<beans xmlns="http://www.springframework.org/schema/beans" 
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
      xsi:schemaLocation="http://www.springframework.org/schema/beans 
     http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> 

     <bean id="dataSource" 
      class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 
     <property name="driverClassName" value="com.mysql.jdbc.Driver" /> 
     <property name="url" value="jdbc:mysql://localhost/Rubrica?" /> 
     <property name="username" value="user" /> 
     <property name="password" value="password" /> 
     </bean> 

     <bean id="JDBCEntryDAO" class="net.tirasa.jdbc_spring_addressbook"> 
     <property name="JDBC_Spring_EntryDAO" ref="JDBC_Spring_EntryDAO" /> 
     </bean>  
    </beans> 

當我運行的應用程序,我得到一個空指針異常(在指定的線),我無法連接到數據庫,這是方法拋出該異常:

@Override 
    public List<Entry> list() { 
     List<Entry> res = new ArrayList<Entry>(); 
     String sql = "SELECT * FROM Person"; 

     try { 
      //open connection    

      Connection conn = datasource.getConnection(); //<----NULL POINTER EXCEPTION 

      //prepare the statement 
      PreparedStatement ps = conn.prepareStatement(sql); 

      //execute 
      ResultSet resultSet = ps.executeQuery(sql); 

      //populate entry 
      while (resultSet.next()) { 
       Entry entry = new Entry(); 
       entry.setId(resultSet.getInt("id")); 
       entry.setCn(resultSet.getString("cn")); 
       entry.setSn(resultSet.getString("sn")); 
       entry.setPn(resultSet.getString("pn")); 
       res.add(entry); 
      } 
      resultSet.close(); 
      ps.close(); 
      conn.close(); 
     } catch (SQLException ex) { 
      Logger.getLogger(JDBC_Spring_EntryDAO.class.getName()).log(Level.SEVERE, null, ex); 
     } 
     return res; 
    } 
+0

數據源未正確初始化。例如。不是自動裝配的。可能有很多原因。在這裏發佈您的應用程序上下文配置以及如何初始化數據源 – StanislavL

+0

您如何注入dataSource?,@Inject私有DataSource數據源? – paul

+0

@StanislavL我使用datasource.xml來設置數據源,這是我發佈的文件。使用這個文件是否正確? – MdC

回答

1

我覺得你需要注入數據源

<bean id="JDBCEntryDAO" class="net.tirasa.jdbc_spring_addressbook"> 
    <property name="JDBC_Spring_EntryDAO" ref="JDBC_Spring_EntryDAO" /> 
    <property name="dataSource" ref="dataSource" /> 
    </bean> 
相關問題