//在这里我定义了我使用的所有类和接口
//服务接口
public interface CustomerService {
public void addCustomer(CustomerTO cto);
}
//服务类实现
public class CustomerServiceImpl implements CustomerService {
@Autowired
CustomerDAO cdao=null;
public void addCustomer(CustomerTO cto){
cdao.addCustomer(cto);
}
}
//CustomerTO类
public class CustomerTO {
private int cid;
private String cname;
private String email;
private long phone;
private String city;
public CustomerTO(int cid, String cname, String email, long phone,
String city) {
this.cid = cid;
this.cname = cname;
this.email = email;
this.phone = phone;
this.city = city;
}
//Setter and Getters
public class JdbcCustomerDAO implements CustomerDAO {
@Autowired
JdbcTemplate jdbcTemp;
public void addCustomer(CustomerTO cto){
String sql="insert into customer values(?,?,?,?,?)";
Object ar[]={cto.getCid(),cto.getCname(),cto.getEmail(),cto.getPhone(),cto.getCity()};
jdbcTemp.update(sql,ar);
}
//客户端代码
public class Lab24Client {
public static void main(String[] args) {
ApplicationContext ctc=new ClassPathXmlApplicationContext("applicationContext.xml");
CustomerService c=(CustomerService)ctc.getBean("cs");
//add Customer
CustomerTO cust=new CustomerTO(102,"vsa","vsa@gmail.com",6154,"Pune");
c.addCustomer(cust);
}
//客户DAO
public interface CustomerDAO {
public void addCustomer(CustomerTO cto);
}
//spring ApplicationContext.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<bean id="dataSource class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost/vik"/>
<property name="username" value="root"/>
</bean>
<bean id="jdbcTemp" class="org.springframework.jdbc.core.JdbcTemplate" autowire="constructor"/>
<bean id="cdao" class="com.jlc.JdbcCustomerDAO"/>
<bean id="cs" class="com.jlc.CustomerServiceImpl"/>
//CustomerRowMapper
public class CustomerRowMapper implements RowMapper<CustomerTO>{
@Override
public CustomerTO mapRow(ResultSet rs, int rn) throws SQLException {
CustomerTO cto=new CustomerTO();
cto.setCid(rs.getInt(1));
cto.setCname(rs.getString(2));
cto.setEmail(rs.getString(3));
cto.setPhone(rs.getLong(4));
cto.setCity(rs.getString(5));
return cto;
}
}
//当我运行客户端时,我得到了以下异常
Exception in thread "main" java.lang.NullPointerException
at com.spring.CustomerServiceImpl.addCustomer(CustomerServiceImpl.java:11)
at com.spring.Lab24Client.main(Lab24Client.java:12)
//请告诉我我在代码中犯了什么错误或者下面的程序有什么问题