6

I'm trying to take advantage of @Value annotation and auto-populate my string-variable from the properties file, but with no luck. Values are not being set and are null.

Here is my configuration:

SendMessageController.java

@RestController
public class SendMessageController {

    @Value("${client.keystore.type}")
    private static String keystoreType;

    @RequestMapping(value = "/sendMessage", method = RequestMethod.POST)
    public ResponseEntity<SendMessageResponse> sendMessage(@Validated @RequestBody SendMessageRequest messageRequest) {
    .......
    }

application.properties

client.keystore.type=JKS

rest-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">


    <context:component-scan base-package="org.example.controllers" />

    <context:property-placeholder location="classpath:application.properties"/>

    <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
    <mvc:annotation-driven />

</beans>

When I run my application and try to access keystoreType variable it is always null. What am I doing wrong?

Oleg
  • 2,984
  • 8
  • 43
  • 71

2 Answers2

16

Spring can not inject @Value to a static field directly.

you can either add inject the value through an annotated setter like this:

private static String keystoreType;

@Value("${client.keystore.type}")
public void setKeystoreType(String keystoreType) {
    SendMessageController.keystoreType = keystoreType;
} 

Or Change :

    @Value("${client.keystore.type}")
    private static String keystoreType;

to :

@Value("${client.keystore.type}")
private String keystoreType;
Rafik BELDI
  • 4,140
  • 4
  • 24
  • 38
1

For the ones still facing the issue after all the preceding suggestions, make sure you are not accessing that variable before the bean has been constructed as described in this answer.

Philippe Simo
  • 1,353
  • 1
  • 15
  • 28