Using Spring Boot, I have a controller like this:
public void foo(FooArgs args)
where:
public class FooArgs {
public int animal;
// ... getters and setters omitted
}
I want to provide a default value of animal
. I can do that like this:
public class FooArgs {
public int animal = -1;
}
Now the -1
is hardcoded and I have to recompile the code if I want to change the default.
How can the default come from a config file, so that code does not need to be recompiled if I want to change the default value?
Using Spring Boot, I have a controller like this:
public void foo(FooArgs args)
where:
public class FooArgs {
public int animal;
// ... getters and setters omitted
}
I want to provide a default value of animal
. I can do that like this:
public class FooArgs {
public int animal = -1;
}
Now the -1
is hardcoded and I have to recompile the code if I want to change the default.
How can the default come from a config file, so that code does not need to be recompiled if I want to change the default value?
You can use application.yml
or application.properties
for that. In the YAML version you can define the default value
animal-initial: -1
and then inside your class use the @Value
annotation to take it from the configuration without recompiling the code.
@Configuration
public class FooArgs {
@Value("${animal-initial}")
private int animal;
}
Spring uses reflection to inject the initial value, so you don't even need a setter in order to load it correctly. Because it Spring loads the value every time you redeploy the application, you don't have to recompile the code, only redeploy to your app container like Tomcat or whatever. Also note that FooArgs
has to be a bean, I used the stereotype @Configuration
, but you can use other methods as well.
If you don't know where to place the config, read https://stackoverflow.com/a/61101598/7769052.