我正在使用 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().getCustomerName()
时,CustomerDAO 中的这段代码 new CustomerDTO();
给出 null
>。我正在考虑使用默认值初始化该字段。
使用/不使用 Spring 框架如何实现这一目标?
最佳答案
尝试使用 Spring
@Value("myValue")
String customerName;
如果没有 spring,只需在声明本身中赋值即可,
private String customerName="myValue";
关于java - 在 Spring bean 中实现空对象设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17522973/