[英]Implementing Null Object Design Pattern in Spring beans
我使用的是CustomerDTO:
public class CustomerDTO {
private int customerId;
private String customerName;
private String customerAddress;
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getCustomerAddress() {
return customerAddress;
}
public void setCustomerAddress(String customerAddress) {
this.customerAddress = customerAddress;
}
}
然后我使用CustomerDAO,我根據customerId獲取客戶
public class CustomerDAO {
private CustomerDTO customer;
public void setCustomer(CustomerDTO customer) {
this.customer = customer;
}
public CustomerDTO getCustomer(int customerId){
try{
if("you get customer based on customer id") then "return the customer";
}catch(Exception ex){
return new CustomerDTO();
//some other work
}
}
}
現在這段代碼new CustomerDTO();
當我嘗試訪問new CustomerDTO().getCustomerName()
時,CustomerDAO中的值為null
。 我正在考慮使用默認值初始化字段。
如何使用/不使用Spring框架實現此目的?
嘗試使用Spring
@Value("myValue")
String customerName;
沒有彈簧,只需在聲明中賦值,
private String customerName="myValue";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.