java - How to set default request params in Spring so that I don't have to hardcode the defaults? - Stack Overflow

admin2025-05-02  0

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?

Share Improve this question edited Jan 2 at 12:46 Mark Rotteveel 110k232 gold badges156 silver badges225 bronze badges asked Jan 2 at 0:57 morpheusmorpheus 20.5k29 gold badges110 silver badges188 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 3

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.

转载请注明原文地址:http://anycun.com/QandA/1746138196a92102.html