2013-04-09 92 views
0

首先,這是在DAO類爲什麼Java在調用其他類的方法時返回java.lang.NullPointerException? (解決)

package com.qt.bm.dao; 

import java.util.List; 

import org.hibernate.Query; 
import org.hibernate.SessionFactory; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Repository; 

import com.qt.bm.form.Customer; 

@Repository 
public class CustomerDAOImpl implements CustomerDAO { 

@Autowired 
private SessionFactory sessionFactory; 

public void addCustomer(Customer customer) { 
    sessionFactory.getCurrentSession().save(customer); 

} 

@SuppressWarnings("unchecked") 
public List<Customer> customerList() { 
    return sessionFactory.getCurrentSession().createQuery("FROM Customer").list(); 
} 

public boolean checkExistingAccount(String account) { 
    Query query = sessionFactory.getCurrentSession().createQuery("FROM Customer WHERE account=:account"); 
    query.setString("account", account); 
    query.setMaxResults(1); 
    if(query.uniqueResult()!=null){ 
     return true; 
    }else{ 
     return false; 
    } 
} 
} 

,這是服務類

package com.qt.bm.service; 

import java.util.List; 

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Service; 
import org.springframework.transaction.annotation.Transactional; 

import com.qt.bm.dao.CustomerDAO; 
import com.qt.bm.form.Customer; 

@Service 
public class CustomerServiceImpl implements CustomerService { 

@Autowired 
private CustomerDAO customerDAO; 

@Transactional 
public void addCustomer(Customer customer) { 
    customerDAO.addCustomer(customer); 

} 
@Transactional 
public List<Customer> customerList() { 
    return customerDAO.customerList(); 
} 
@Transactional 
public boolean checkExistingAccount(String account) { 
    return customerDAO.checkExistingAccount(account); 
} 
} 

以及控制器

package com.qt.bm.controller; 

import java.text.SimpleDateFormat; 
import java.util.Date; 
import java.util.Map; 

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.beans.propertyeditors.CustomDateEditor; 
import org.springframework.stereotype.Controller; 
import org.springframework.validation.BindingResult; 
import org.springframework.web.bind.WebDataBinder; 
import org.springframework.web.bind.annotation.InitBinder; 
import org.springframework.web.bind.annotation.ModelAttribute; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 

import com.qt.bm.form.Customer; 
import com.qt.bm.service.CustomerService; 
import com.qt.bm.validator.CustomerValidator; 

@Controller 
public class CustomerController { 

@InitBinder 
public void initBinder(WebDataBinder binder){ 
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); 
    dateFormat.setLenient(false); 

    // true passed to CustomDateEditor constructor means convert empty String to null 
    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); 
} 
@Autowired 
CustomerService customerService; 

@RequestMapping("customer") 
public String listCustomer(Map<String, Object> map){ 
    map.put("customer", new Customer()); 

    return "customer"; 
} 

@RequestMapping(value="/addCustomer", method = RequestMethod.POST) 
public String addCustomer(@ModelAttribute("customer") Customer customer, BindingResult result){ 

    //check validate customer 
    CustomerValidator customerValidator = new CustomerValidator(); 
    customerValidator.validate(customer, result); 
    if(result.hasErrors()){ 
     System.out.println(result.toString()); 
     return "customer"; 
    } 

    customerService.addCustomer(customer); 
    return "redirect:/customer"; 

} 

} 

下面是一個驗證類從實現彈簧驗證器

package com.qt.bm.validator; 

import java.util.regex.Matcher; 
import java.util.regex.Pattern; 

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.validation.Errors; 
import org.springframework.validation.ValidationUtils; 
import org.springframework.validation.Validator; 

import com.qt.bm.form.Customer; 
import com.qt.bm.service.CustomerService; 

public class CustomerValidator implements Validator { 

@Autowired 
CustomerService customerService; 

private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@" 
     + "[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; 

public boolean supports(Class<?> c) { 
    return Customer.class.isAssignableFrom(c); 
} 

public void validate(Object customerTarget, Errors errors) { 
    // check empty 
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "account", 
      "NotEmpty.customer.account"); 
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", 
      "NotEmpty.customer.password"); 
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "customerName", 
      "NotEmpty.customer.customerName"); 
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "dateOfBirth", 
      "NotEmpty.customer.dateOfBirth"); 
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", 
      "NotEmpty.customer.email"); 
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address", 
      "NotEmpty.customer.address"); 
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "phone", 
      "NotEmpty.customer.phone"); 

    Customer customer = (Customer) customerTarget; 

    // check account 
    if (!customer.getAccount().equals("")) { 
     String account = customer.getAccount(); 
     System.out.println(account); 
     boolean existingAccount =false; 

Problem here ->>> existingAccount = customerService.checkExistingAccount(customer.getAccount()); 

     if (existingAccount) { 
      errors.rejectValue("account", "Exist.customer.account"); 
     } 
    } 

    // check password 
    if (customer.getPassword() != customer.getRePassword()) { 
     errors.rejectValue("rePassword", "NotMatch.customer.rePassword"); 
    } 

    // check dateOfBirth 

    // check email 
    /*if (!customer.getEmail().equals("")) { 
     Boolean emailIsExisting = customerService.checkExistingCustomer("", 
       customer.getEmail()); 
     if (emailIsExisting) { 
      errors.rejectValue("email", "Exist.customer.email"); 
     } 
    }*/ 
    Pattern emailPattern = Pattern.compile(EMAIL_PATTERN); 
    Matcher emailMatcher = emailPattern.matcher(customer.getEmail()); 
    if (!emailMatcher.matches()) { 
     errors.rejectValue("email", "WrongFormat.customer.email"); 
    } 

} 
} 

這種說法總是返回NullPointerExeption,而我在這

existingAccount = customerService.checkExistingAccount(customer.getAccount()); 

任何想法stucking?

感謝你們這麼多,我已經解決了這個問題

我刪除的CustomerValidator的@Autowired註解和更換由

public class CustomerValidator implements Validator { 


private final CustomerService customerService; 

public CustomerValidator(CustomerService customerService) { 
    this.customerService = customerService; 
} 

然後我通過向客服,這是在使用@Autowired註解控制器,所述的CustomerValidator初始化

@RequestMapping(value="/addCustomer", method = RequestMethod.POST) 
public String addCustomer(@ModelAttribute("customer") Customer customer, BindingResult result){ 

    //check validate customer 
    CustomerValidator customerValidator = new CustomerValidator(customerService); 
    customerValidator.validate(customer, result); 
    if(result.hasErrors()){ 
     System.out.println(result.toString()); 
     return "customer"; 
    } 

    customerService.addCustomer(customer); 
    return "redirect:/customer"; 

} 
+0

發佈您的彈簧配置。 – 2013-04-09 09:19:35

+0

您可以調試並讓我們知道'customerService'或'customer'是否爲'null'?這會幫助你更輕鬆。 – 2013-04-09 09:19:39

+0

'customerService'的自動裝配失敗。 'customer'不能爲null,因爲它之前已經被訪問過。 – Kai 2013-04-09 09:19:49

回答

0

要麼customerServicecustomer參考 一片空白。調用的空引用任何方法都將拋出NullPointerException

+0

這或許可以用作評論。但我想象OP正在尋找原因*爲什麼*這些項目是空的,所以我不認爲這是一個很好的答案。 – 2013-04-09 09:20:21

4

你不能做到這一點

CustomerValidator customerValidator = new CustomerValidator(); 

,並期望這個自動裝配工作:

@Autowired 
CustomerService customerService; 

customerService將是無效這就是爲什麼你得到一個NPE。

創建在Spring中的CustomerValidator和電線入。

+0

謝謝,你說得對,我過度使用了@Autowired:D – 2013-04-09 10:23:41

0

你有沒有制定者的CustomerService?

+0

如果這是你的答案,你不應該把它當作一個問題來形容。問題應作爲評論發佈。 – Kai 2013-04-09 09:21:12

0

確保您有組件掃描設置,以檢查包的bean註釋,以便在容器中創建這些bean。

<context:component-scan base-package="com.qt.bm.dao,com.qt.bm.service" /> 
1

依賴注入只適用於Spring管理的bean。

@Autowired // you are telling spring to inject dependency. 
CustomerService customerService; 

在您的代碼中,您正在使用new運算符創建CustomerValidator bean。

CustomerValidator customerValidator = new CustomerValidator(); // wrong 

在這種情況下,這個bean不是由Spring管理的,依賴關係也不會被注入到這個bean中。

您應該聲明CustomerValidator bean,因爲您聲明瞭CustomerService。

@Autowired 
CustomerService customerService; 

@Autowired 
CustomerValidator customerValidator; // delcare spring managed validator bean 

,並添加的CustomerValidator類@Component註解。

@Component 
public class CustomerValidator implements Validator { 
+0

謝謝,但它不起作用 – 2013-04-09 10:25:52

相關問題