简体   繁体   中英

Implementing Null Object Design Pattern in Spring beans

I am using a 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;
    }

}

Then I am using CustomerDAO where I am fetching customer based on the 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
        }
    }
}

Now this code new CustomerDTO(); in CustomerDAO is giving null when I am trying to access new CustomerDTO().getCustomerName() . I am thinking about initializing the field with default values.

How can I achieve this with/without Spring framework?

Try with Spring

@Value("myValue")
String customerName;

And without spring, just assign value in declaration itself,

 private String customerName="myValue";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM