I like Zakaria's answer, but if you're in a project where your team doesn't want to use that approach, and you're stuck trying to construct something with a String, integer, float, or primative type from a property file into the constructor, then you can use Spring's @Value
annotation on the parameter in the constructor.
For example, I had an issue where I was trying to pull a string property into my constructor for a class annotated with @Service
. My approach works for @Service
, but I think this approach should work with any spring java class, if it has an annotation (such as @Service
, @Component
, etc.) which indicate that Spring will be the one constructing instances of the class.
Let's say in some yaml file (or whatever configuration you're using), you have something like this:
some:
custom:
envProperty: "property-for-dev-environment"
and you've got a constructor:
@Service // I think this should work for @Component, or any annotation saying Spring is the one calling the constructor.
class MyClass {
...
MyClass(String property){
...
}
...
}
This won't run as Spring won't be able to find the string envProperty
. So, this is one way you can get that value:
class MyDynamoTable
import org.springframework.beans.factory.annotation.Value;
...
MyDynamoTable(@Value("${some.custom.envProperty}) String property){
...
}
...
In the above constructor, Spring will call the class and know to use the String "property-for-dev-environment"
pulled from my yaml configuration when calling it.
NOTE: this I believe @Value annotation is for strings, intergers, and I believe primative types. If you're trying to pass custom classes (beans), then approaches in answers defined above work.