java - 在 Spring bean 中实现空对象设计模式

标签 java oop design-patterns null spring-3

我正在使用 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/

相关文章:

java - StringBuilder 子串和反向 - Java

java - 在程序中删除抽象类的对象

php - Codeigniter 在回调中传递两个值(form_validation)

ios - 我怎样才能改进这个涉及 NSDate 比较的实现?

c++ - 依赖注入(inject)/继承设计模式的构造函数参数太多

java - 在 Jenkins 中运行自定义数据库脚本

java - 尝试每 24 小时调用一次函数

php - PHP 中的美元符号是什么意思?

C++ OOP 无法正确存储和显示内容

design-patterns - 应用工程和用户数量