我正在使用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();时,CustomerDAO中的此代码null给出了new CustomerDTO().getCustomerName()。我正在考虑使用默认值初始化该字段。

如何在有/没有Spring框架的情况下实现这一目标?

最佳答案

尝试春季

@Value("myValue")
String customerName;


而且没有弹簧,只需在声明本身中分配值,

 private String customerName="myValue";

09-25 16:14