jeudi 23 août 2018

What is the best way to set this class's member variable with a value from a .properties file?

I have several entity classes (using Spring) that also have "helper" classes associated with them that offer additional functionality. A very simplified example:

public class Contact {

    private Integer contactId;
    private String name;
    private int age;

    // Provide access to helper class
    @Transient
    public ContactHelper getContactHelper() {
        return new ContactHelper(this);
    }

    // Getters/Setters omitted
}

public class ContactHelper {

    private static String contactUrlPattern = "http://localhost/GetContact.action?contactId=[id]";

    private Contact contact;
    public ContactHelper(Contact contact) {
        this.contact = contact;
    }

    public String getContactLink() {
        return  contactUrlPattern.replace("[ID]", this.contact.getContactId());
    }

    public void setContactUrlPattern(String str) {
        contactUrlPattern = str;
    }
}

This setup provides a very convenient pattern especially when displaying values. For example, I can now write:

<a href="${contact.contactHelper.contactLink}">${contact.name}</a>

The issue now is I would like to set the contactUrlPattern with a different value from a "production" properties file (change 'localhost' to 'example.com'). Normally I would inject a value using Spring, but since this pattern create a new ContactHelper each time, it is not a part of the Spring Context.

What is the best way to go about setting this variable? I could possibly set it after the ApplicationContext is initialized in a listener since the variable is static. I would have to set about 10-15 different "helpers" and variables -- or is that wreak of code smell?

Aucun commentaire:

Enregistrer un commentaire