I have a properties class below in my spring-boot project.
#Component
#ConfigurationProperties(prefix = "myprefix")
public class MyProperties {
private String property1;
private String property2;
// getter/setter
}
Now, I want to set default value to some other property in my application.properties file for property1. Similar to what below example does using #Value
#Value("${myprefix.property1:${somepropety}}")
private String property1;
I know we can assign static value just like in example below where "default value" is assigned as default value for property,
#Component
#ConfigurationProperties(prefix = "myprefix")
public class MyProperties {
private String property1 = "default value"; // if it's static value
private String property2;
// getter/setter
}
How to do this using #ConfigurationProperties class (rather typesafe configuration properties) in spring boot where my default value is another property ?
Check if property1 was set using a #PostContruct in your MyProperties class. If it wasn't you can assign it to another property.
#PostConstruct
public void init() {
if(property1==null) {
property1 = //whatever you want
}
}
In spring-boot 1.5.10 (and possibly earlier) setting a default value works as-per your suggested way. Example:
#Component
#ConfigurationProperties(prefix = "myprefix")
public class MyProperties {
#Value("${spring.application.name}")
protected String appName;
}
The #Value default is only used if not overridden in your own property file.
Related
I have a class with inject attributes like so:
#RestController
public class MyController {
private final String myValue;
#Autowired
public MyController(
#Value("${config.myValue}") String myValue) {
this.myValue = myValue;
}
#PostMapping("/dostuff")
public String dostuff(#RequestBody String message) {
// stuff
}
}
And then I have a config file defined inside src/main/resources/application.yml like so:
config:
myValue: "some value"
But my IntelliJ (and cmd) tell me the value is not found:
Could not resolve placeholder 'config.myValue' in value "${config.myValue}"
Why is my defined value not being recognized? (I tried renaming file to application-default.yml and application.properties but that didn't help either)
Could you please try renaming file as application.properties and define property like below and check if it works?
config.myValue = some value
How to inject values from yaml and set default values if a property is not defined in the yaml props file? Is using both ConfigurationProperties and Value like below a good use? If not how else can we achieve it?
Properties file
app:
prop1: test
prop2: true
map:
key1: value1
key2: value2
Java class:
#Data
#Validated
#ConfigurationProperties("app")
public class properties {
private String prop1;
#Value("${app.prop2:default}")
private Boolean prop2;
#NestedConfigurationProperty
#NotNull
private Map<String,String> prop3;
}
Is using both ConfigurationProperties and Value like below a good use
No. #ConfigurationProperties indicates to spring that it should bind the java fields based on their name to some matching properties. However to achieve that spring requires that the class that has this annotation must be a spring bean (proxy class). So you have to use it together with either #Configuraiton or #Component or some other annotation that creates a spring bean for this class.
There is also some other functionality available where you can use another annotation #EnableConfigurationProperties(properties.class) on some other spring bean (not the current class that has the #ConfigurationProperties annotation)
Most common is that you use the #Configuration and then spring will be able to create a spring bean (proxy of this class) and then bind the values that you expect on the fields that you have.
Since you already have the #ConfigurationProperties("app"), then the property with the name prop2 will be bound with the application property app.prop2
#Data
#Validated
#Configuration <---------------
#ConfigurationProperties("app")
public class properties {
private String prop1;
private Boolean prop2;
#NestedConfigurationProperty
#NotNull
private Map<String,String> prop3;
}
If your problem is the default values in case the properties do not exist at all in application.properties then you can just initialize those java fields with some values.
#Data
#Validated
#Configuration <---------------
#ConfigurationProperties("app")
public class properties {
private String prop1 = "default";
private Boolean prop2 = false;
#NestedConfigurationProperty
#NotNull
private Map<String,String> prop3;
}
I realized a strange behavior in SpringBoot.
In a yml file I have the following configuration:
main:
record-id:
start-position: 1
value: 1
enabled: true
record-name:
start-position: 2
value: main
enabled: true
invented:
start-position: 3
value: 01012020
enabled: false
And these are the classes for it:
public class FieldType {
private Integer startPosition;
private String value;
private Boolean enabled;
getters/setters
}
#Component
#ConfigurationProperties(prefix = "main")
public class Main {
private FieldType recordId;
private FieldType recordName;
private FieldType invented;
getters/setters <-- sometimes without getters
}
As you can see, the main class has #ConfigurationProperties annotation to load the properties from yml into that bean.
And here is what I have found:
if I don't provide getters for the fields in the main class, then sometimes the fields in the main call stay null, so not initiated
if I restart the SpringBoot, then randomly other (1 or more) fields stay null, so not initiated
if I restart the SpringBoot n times, then, again and again, random fields stay null
if I provide getters for the fields in the main class, then all the fields will be always instantiated from tye yml file, no matter how many times I restart SpringBoot
Why is this? Why SpringBoot requires getters for fields which represent properties in yml?
You don't need getter's to bind the properties, you need setters to bind properties if you are using default constructor, docs
If nested POJO properties are initialized (like the Security field in the preceding example), a setter is not required. If you want the binder to create the instance on the fly by using its default constructor, you need a setter.
In case if you are initializing the FieldType in Main class, then you don't need setters as well
#Component
#ConfigurationProperties(prefix = "main")
public class Main {
private FieldType recordId = new FieldType();
private FieldType recordName = new FieldType();
private FieldType invented = new FieldType();
}
You can also use Constructor binding by completely avoiding setters
public class FieldType {
private Integer startPosition;
private String value;
private Boolean enabled;
public FieldType(Integer startPosition, String value, Boolean enabled) {
this.startPosition = startPosition;
this.value = value;
this.enabled = enabled
}
#ConstructorBinding
#ConfigurationProperties(prefix = "main")
public class Main {
private FieldType recordId;
private FieldType recordName;
private FieldType invented;
public Main(FieldType recordId,FieldType recordName,FieldType invented) {
this.recordId = recordId;
this.recordName = recordName;
this.invented = invented;
}
Just a note on Constructor Binding
To use constructor binding the class must be enabled using #EnableConfigurationProperties or configuration property scanning. You cannot use constructor binding with beans that are created by the regular Spring mechanisms (e.g. #Component beans, beans created via #Bean methods or beans loaded using #Import)
I have the following enum:
public enum MyEnum {
NAME("Name", "Good", 100),
FAME("Fame", "Bad", 200);
private String lowerCase;
private String atitude;
private long someNumber;
MyEnum(String lowerCase, String atitude, long someNumber) {
this.lowerCase = lowerCase;
this.atitude = atitude;
this.someNumber = someNumber;
}
}
I want to setup the someNumber variable different for both instances of the enum using application.properties file.
Is this possible and if not, should i split it into two classes using an abstract class/interface for the abstraction?
You can't/shouldn't change values of a enum in Java. Try using a class instead:
public class MyCustomProperty {
// can't change this in application.properties
private final String lowerCase;
// can change this in application.properties
private String atitude;
private long someNumber;
public MyCustomProperty (String lowerCase, String atitude, long someNumber) {
this.lowerCase = lowerCase;
this.atitude = atitude;
this.someNumber = someNumber;
}
// getter and Setters
}
Than create a custom ConfigurationProperties:
#ConfigurationProperties(prefix="my.config")
public class MyConfigConfigurationProperties {
MyCustomProperty name = new MyCustomProperty("name", "good", 100);
MyCustomProperty fame = new MyCustomProperty("fame", "good", 100);
// getter and Setters
// You can also embed the class MyCustomProperty here as a static class.
// For details/example look at the linked SpringBoot Documentation
}
Now you can change the values of my.config.name.someNumber and my.config.fame.someNumber in the application.properties file. If you want to disallow the change of lowercase/atitude make them final.
Before you can use it you have to annotate a #Configuration class with #EnableConfigurationProperties(MyConfigConfigurationProperties.class). Also add the org.springframework.boot:spring-boot-configuration-processor as an optional dependency for a better IDE Support.
If you want to access the values:
#Autowired
MyConfigConfigurationProperties config;
...
config.getName().getSumeNumber();
Well what you can do is the following:
Create a new class: MyEnumProperties
#ConfigurationProperties(prefix = "enumProperties")
#Getter
public class MyEnumProperties {
private Map<String, Long> enumMapping;
}
Enable ConfigurationProperties to your SpringBootApplication/ any Spring Config via
#EnableConfigurationProperties(value = MyEnumProperties.class)
Now add your numbers in application.properties file like this:
enumProperties.enumMapping.NAME=123
enumProperties.enumMapping.FAME=456
In your application code autowire your properties like this:
#Autowired
private MyEnumProperties properties;
Now here is one way to fetch the ids:
properties.getEnumMapping().get(MyEnum.NAME.name()); //should return 123
You can fetch this way for each Enum value the values defined in your application.properties
I have a bean class like, for example
class Sample {
private String message;
public void setMessage(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
and I want to set this property's value.
In Xml Configuration, I could do
<bean id = "sample" class = "Sample"
<property name = "message" value = "Hello there!"/>
</bean>
How do I achieve the same thing i.e. set property's value using Java Annotation? Now I have read that we can use #Value annotation using some properties file but cannot it be done without using properties file, doing the way I did it through xml file? Or using properties file is necessary?
I was able to do it by including #Value("Hello there!") above the setter method. But I could feel that is not a good idea. How to set the property values for different instances using Java Annotations?
Thanks.
The value inserted into the #Value can come from places other than a properties file, for example it can also use system properties.
Using the guide here as a starting point should help you understand a little better.
As a basic and mostly useless usage example we can only inject “string
value” from the annotation to the field:
#Value("string value")
private String stringValue;
Using the #PropertySource annotation allows us to work with values
from properties files with the #Value annotation. In the following
example we get “Value got from the file” assigned to the field:
#Value("${value.from.file}")
private String valueFromFile;
We can also set the value from system properties with the same syntax.
Let’s assume that we have defined a system property named systemValue
and look at the following sample:
#Value("${systemValue}")
private String systemValue;
Default values can be provided for properties that might not be
defined. In this example the value “some default” will be injected:
#Value("${unknown.param:some default}")
private String someDefault;
You have a few options, depending on your requirements. In both of these examples you can set the annotation on a setter instead of the field.
Custom PropertySource
This lets you continue using #Value with greater control for how the properties are supplied. There are a large number of PropertySource implementations, but you can always create your own.
References:
How to add custom property source to Spring's Environment
PropertySource JavaDoc
Example:
#Configuration
class MyConfiguration {
#Bean
PropertySource myPropertySource(ConfigurableEnvironment env) {
MapPropertySource source = new MapPropertySource("myPropertySource", singletonMap("myPropertyValue", "example"));
env.getPropertySources().addFirst(source);
return source;
}
}
class Sample {
#Value("${myPropertyValue}")
private String message;
public String getMessage() {
return message;
}
}
String Bean
Define a bean as a String and auto-wire it using its qualifier.
Example:
#Configuration
class MyConfiguration {
#Bean
String myPropertyValue() {
String value;
// do something to get the value
return value;
}
}
class Sample {
#Autowired
#Qualifier("myPropertyValue")
private String message;
public String getMessage() {
return message;
}
}