A Java lightweight configuration framework for all kinds of configurations (commandline, files, etc.)
- Zero configuration: No file configurations, all in codes
- Extensive: Just extends the abstract class or interface
- Lightweight: A few dependencies, make up a world
<dependency>
<groupId>io.tomahawkd</groupId>
<artifactId>jlightconfig</artifactId>
<version>1.0.1</version>
</dependency>
Note: The example below is already integrated in this repo
- Extends abstract class
AbstactConfig
and define your parse method
Example (with dependency com.beust.jcommander:1.69
):
@SourceFrom(CommandlineConfigSource.class)
public class CommandlineConfig extends AbstractConfig {
@HiddenField
private JCommander c;
@Override
public final void parse(@NotNull ConfigSource source) {
c = JCommander.newBuilder().addObject(this)
.addObject(getDelegates()).build();
try {
c.parse((String[]) source.getData());
} catch (ParameterException e) {
System.err.println(e.getMessage());
c.usage();
throw e;
}
}
public String usage() {
StringBuilder builder = new StringBuilder();
c.usage(builder);
return builder.toString();
}
}
-
Create delegates to parse and receive config data
-
Use annotation
BelongsTo
to your Delegate bind your config and delegate
Note: You may use AbstractConfigDelegate.getField(String key, Class<T> type)
to get data from your configs or delegates
Example:
@BelongsTo(CommandlineConfig.class)
public class TestDelegate extends AbstractConfigDelegate {
@Parameter(names = {"-h", "--help"}, help = true,
description = "Prints usage for all the existing commands.")
private boolean help;
public boolean isHelp() {
return help;
}
}
-
Implements interface
ConfigSource
and implements how data could be received. -
Use annotation
SourceFrom
to your Config to bind source and config
Example:
public class CommandlineConfigSource implements ConfigSource {
private String[] data;
public void setData(String[] data) {
this.data = data;
}
@Override
public String[] getData() {
return data;
}
}
- Use
SourceManager
andConfigManager
to run your project.
Example:
class Test {
// args: --help
public static void main(String[] args) {
SourceManager sourceManager = SourceManager.get();
ConfigManager configManager = ConfigManager.get();
sourceManager.getSource(CommandlineConfigSource.class).setData(args);
configManager.parse();
// you would get true
configManager.getConfig(CommandlineConfig.class)
.getDelegateByType(TestDelegate.class).isHelp();
// or you could use
configManager.getConfig(CommandlineConfig.class)
.getDelegateByString("io.tomahawkd.config.delegate.TestDelegate")
.getField("help", boolean.class);
}
}
- Test failed in maven
While maven testing the sources, it could report Reflections Scanner was not configured ronmamo/reflections (#273)
This repo is under Apache v2.0 license