Volte
Volte

Reputation: 1905

How do I dynamically assign enum values using java spring bean

I've got the following code:

package vb4.email;

import org.springframework.beans.factory.annotation.Value;

public enum ValidAddresses {

    // TODO: Is there a cleaner way to switch debugs?
    // How do we make this bean-able?

    @Value("${email.addresses.defaults.support}")
    DEFAULT_SUPPORT_ADDRESS("[email protected]"),
    @Value("${email.addresses.defaults.performance}")
    DEFAULT_PERFORMANCE_SUPPORT_ADDRESS("[email protected]");

    private final String email;

    private ValidAddresses(final String email){
        this.email = email;
    }

    @Override
    public String toString()
    {
        return this.email;
    }
}

As you can see from my @Value annotations, I'm looking to "beanify" this process. I want the benefits of the enumerable as a construct, but I'd like to make this configurable in our .properties file. Please keep in mind that the .properties file which has all the key=value pairs is used extensively throughout the site.

Please keep your answers on mark; I'm not looking to debate the validity of what is already in place. (Trust me I understand your frustration).

Upvotes: 3

Views: 5216

Answers (1)

onexdrk
onexdrk

Reputation: 121

You can provide setters for your ValidAddresses enum and then use an initializer, smth like

@Configurable
public class EnumValueInitializer {

  @Value("${email.addresses.defaults.support}")
  private String support;

  @PostConstruct
  public void postConstruct() {
    initializeAddressesEnum();
  }

  private void initializeAddressesEnum() {
    ValidAddresses.DEFAULT_SUPPORT_ADDRESS.setEmail(support);
  }

}

I hope it will be helpful. Good luck.

Upvotes: 7

Related Questions