String.format returns null in Spring Boot after retrieving information from application.properties - spring

I have a Spring Boot application, using Intellij, and am trying to use the #Value annotation in order to get an environment variable from my application.properties.
My application.properties looks like this
server.port=27019
web.entrance.id=63d284ec
Using debugger, I can see that the value of entranceId is successfully retrieved from application.properties, but the same variable is always null in the String.format and my WebUrl has the string 'null' in it and I don't understand why.
#RestController
public class Controller {
#Value(("${entrance.id}"))
private String entranceId;
String WebUrl = String.format("http://localhost:27019/%s", entranceId);
Can someone explain if there is some detail I'm missing why this happens?
Thank you

Your thinking is wrong. Spring will process the #Value after the object has been constructed, whereas your field is being initialized as soon as the class is being constructed (so during constructing).
Basically what Spring does
new Controller()
Detect #Value and with reflection set value
Any construction callbacks (like #PostConstruct).
Your field is being filled at step 1 not after step 2. At which point the #Value hasn't yet been processed.
If you want to set the value you need to do that in an #PostConstruct method or use constructor injection to construct the URL.

Related

Kotlin Spring boot #Value annotation process

#Value("\${datasource.host}")
private val host: String = ""
I wrote the following code in KOTLIN and it worked fine.
I don't understand how the host was injected into the host.
In my knowledge, the value should not be injected because the host variable is val.
How does this code work?
Short answer: Spring is magical!
For a Kotlin property, val doesn't necessarily mean that the property is constant.  (It's not an exact equivalent of Java final here.)  It simply means that there's a get() method but no set() method.
That leaves open the possibility for the value to change some other way.  (For example, the property could have a custom getter which returned different values.)
I'm not sure quite how Spring works its magic; it may be able to set the property's backing field directly, or it may create a hidden subclass which can.  In any case, it's perfectly capable of setting val properties.  (You can also see this in Hibernate.)

Local override for setSerializationInclusion(Include.NON_NULL) in ObjectMapper

In my spring application in WebMvcConfigurerAdapter, CustomObjectMapper is added in HttpMessageConverter. The CustomObjectMapper has setSerializationInclusion(Include.NON_NULL). For 1 particular pojo returned via Spring's ResponseBody I want null properties to be returned as well. I cannot change global setting as it will impact all controllers endpoints. Any suggestions ?
You can create a mixin for the Pojo of interest and set the mixin on your CustomObjectMapper. This other answer shows exactly how to do this.

How to set Spring camel case property with uppercase environment variable?

I have some code to load a value as such in my Spring application:
#Component
public class MyElasticRestService {
#Value("${elasticApi.baseURL}")
private String elasticApiBaseUrl;
According to the Spring docs, I should be able to use a relaxed binding that comes from an uppercase environment variable such as ELASTIC_API_BASE_URL or ELASTICAPI_BASEURL. But I'm confused which is correct. Both don't seem to work so I am wondering how to debug what is actually picked up.
I've loaded Spring Boot Actuator to view the configprops endpoint. But it doesn't have anything on the elasticApi prefix.
What should the correct environment variable be and how can I see how it gets translated and picked up by the application?
The #Value annotation doesn't support relaxed bindings. Therefore you could use a class annotated with #ConfigurationProperties or you use a RelaxedPropertyResolver to get the value from the environment.
According to https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-external-config-vs-value, it is now very possible simply with #Value as long as you use kebab-case (all lower case with dash) for the name e.g. #Value("config.refresh-rate")
Instead of trying to make it an UPPER_SNAKE_CASE, you can put it in your application.yaml file, this way:
elasticApi.baseURL: ${ELASTIC_API_BASE_URL:defaultvalue}
or this way doesn't really matter:
elasticApi:
baseURL: ${ELASTIC_API_BASE_URL:defaultvalue}

What does the #Value annotation in method do?

I see one method annotated with #Value("${some.property}")
as in
#Value("${some.property}")
public void setSomething(String param) {
... do something with param
}
What is that annotation doing there?
Basically it tells Spring's AutowiredAnnotationBeanPostProcessor to call the setSomething method with the resolved value of some.property as the argument... but only if you have a PropertySourcesPlaceholderConfigurer in your bean definitions; if you haven't configured one the post processor will only inject the string "${some.property}"(without quotes) to your method.
An IllegalArgumentException will be thrown if the value could not be resolved unless you have used a default e.g. "${some.property:default}".
Spring resolves these values using the current Environment and its PropertySources e.g. JVM system properties, a Java properties file, etc.
Also you may use Spring Expression Language (SpEL) to resolve things like #{someBean.someMethod} or #{systemProperties[user.region]}
Sidenote: As the documentation states
Fields are injected right after construction of a bean, before any
config methods are invoked. [...] Bean property setter methods [as in this case] are effectively just a special case of such a general config method.
A common mistake is to try to execute some logic in your constructor using the value injected but at this moment the value has not be resolved nor injected because the constructor must finish in order to inject the value in the config method. In these cases you have to use the #Value or #Autowired annotations in your constructor arguments.
You may also use #PostConstruct or the XML init-method attribute pointing to a method that will be executed after the bean properties have been set. Alternatively you can implement the InitializingBean interface.

Update field annotated with #Value in runtime

Let's imagine we have such a component in Spring:
#Component
public class MyComponent {
#Value("${someProperty}")
private String text;
}
If we define the property placeholder:
<context:property-placeholder location="classpath:myProps.properties"/>
And myPropos.properties contains the value for someProperty the value will be injected to the text field when the context is initialized. That's quite simple and easy.
But let's say that I have a service that enables user to change the value of the someProperty:
public void changeProp(String name, String newValue);
Is there a chance I can re-inject the newValue to text field. I mean it should be quite straight forward.. Basically it's nothing different than the after-initialization injection. I can not imagine that Spring does not have support for this? Can I fire some event or something?
I could do this on my own basically, but I wander is it maybe something there already? If not does anyone know what Spring class is in fact handling the injections at the first place? I could probably reuse the code there do perform this on my own if a solution does not exists.
I expect spring does not have a support for this, because the normal injection is done while creating the bean, but not will it is put in service.
Anyway: in this blog entry "Reloadable Application Properties with Spring 3.1, Java 7 and Google Guava", you can find the idea for an solution.
The key idea is to use a post processor to build a list of all fields with property fields. And if the properties are changed on can use this list to update the fields.

Resources