1

//ここで、使用したすべてのクラスとインターフェースを定義します

//サービスインターフェース

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)

//コードでどのような間違いを犯したか、または次のプログラムの問題点を教えてください

4

1 に答える 1

4

以下のコードのような注釈構成を xml で有効化/登録する必要があります。

<context:annotation-config/>
于 2013-02-06T09:06:01.933 に答える