Friday 20 May 2016

Owner: Setting default values to properties

Suppose if any property is missing from property file, we can give a default value for that property by using Default annotation.

ProjectConfig.properties
#Project configurations
imagesDirectory = /Users/harikrishna_gurram/images
videosDirectory = /Users/harikrishna_gurram/videos
maxIcons = 9


ProjectConfig.java
package owner_api_tutorial;

import org.aeonbits.owner.Config;

public interface ProjectConfig extends Config {
 String imagesDirectory();
 String videosDirectory();
 
 @DefaultValue("16")
 int maxIcons();
 
 @DefaultValue("admin@admin.com")
 String adminMail();
}

In above snippet I used DefaultValue annotation on top of the function adminMail(). If the property adminMail is not found in properties file, then it uses the default value "admin@admin.com".

PropertyUtil.java
package owner_api_tutorial;

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.adminMail());
  System.out.println(cfg.imagesDirectory());
  System.out.println(cfg.maxIcons());
  System.out.println(cfg.videosDirectory());

 }
}


Output
admin@admin.com
/Users/harikrishna_gurram/images
9
/Users/harikrishna_gurram/videos


Previous                                                 Next                                                 Home

No comments:

Post a Comment