qq_35260734
2700zc
2018-12-01 02:20

为什么使用@Autowired注入xml里的BasicDataSource会出现空指针异常?

  • spring
  • xml
  • 异常

今天突然想不用mybatis只用Spring来调取mysql的链接,于是这样配置了下,发现在service的实现层获取不到链接,空指针异常,问题代码是出在 connection=ds.getConnection();这句话上 这是为什么?有大佬解决下吗?

        @Service

public class test_serviceIm implements test_service{

@Autowired
DataSource ds;
@Override
public String getString(int i) {
    Connection connection;
    ResultSet rs = null;
    PreparedStatement ps = null;
    String a = null;
    try {
        String sql="SELECT num FROM test_1  where id=?";
        System.out.println(999);
        connection=ds.getConnection();
        connection.prepareStatement(sql);
        ps.setInt(1, i);
        System.out.println(1111);
        while(rs.next()){
            a=rs.getString("num");
        }
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return a;

}
public static void main(String[] args) {
    test_serviceIm tsIm=new test_serviceIm();
    System.out.println(tsIm.getString(1));
}

}



``` <!-- 整合数据源 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>




  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

2条回答

为你推荐