Saturday, 21 May 2016

Java: Owner: Variable Expansion

Variable expansion is very useful feature in developing real world applications.


ProjectConfig.properties
#Project configurations
quote = ${success} ${failure}
success = Success is never final.
failure = Failure is never Fatal. ${courage}
courage = Its courage that counts.........

import org.aeonbits.owner.Config;

public interface ProjectConfig extends Config {

  String quote();

  String success();

  String failure();

  String courage();
}

import org.aeonbits.owner.ConfigFactory;

public class PropertyUtil {
  public static void main(String args[]) throws Exception {
    ProjectConfig cfg = ConfigFactory.create(ProjectConfig.class);

    System.out.println(cfg.quote());
    System.out.println(cfg.success());
    System.out.println(cfg.failure());
    System.out.println(cfg.courage());

  }
}


Output
Success is never final. Failure is never Fatal. Its courage that counts.........
Success is never final.
Failure is never Fatal. Its courage that counts.........
Its courage that counts.........


You can apply variable expansion using annotations also.
import org.aeonbits.owner.Config;

public interface ProjectConfig extends Config {

  @DefaultValue("${success} ${failure}")
  String quote();

  @DefaultValue("Success is never final.")
  String success();

  @DefaultValue("Failure is never Fatal. ${courage}")
  String failure();

  @DefaultValue("Its courage that counts.........")
  String courage();
}

How to disable variable expansion?
You can disable variable expansion using DisableFeature annotation.


@DisableFeature(VARIABLE_EXPANSION)
import static org.aeonbits.owner.Config.DisableableFeature.VARIABLE_EXPANSION;

import org.aeonbits.owner.Config;

public interface ProjectConfig extends Config {

  @DefaultValue("${success} ${failure}")
  @DisableFeature(VARIABLE_EXPANSION)
  String quote();

  @DefaultValue("Success is never final.")
  @DisableFeature(VARIABLE_EXPANSION)
  String success();

  @DefaultValue("Failure is never Fatal. ${courage}")
  @DisableFeature(VARIABLE_EXPANSION)
  String failure();

  @DefaultValue("Its courage that counts.........")
  @DisableFeature(VARIABLE_EXPANSION)
  String courage();
}




Previous                                                 Next                                                 Home

No comments:

Post a Comment