Java - @Value annotation returns null

I am trying to use annotation @Valueand automatically populate my string variable from a properties file, but no luck. Values ​​are not set and 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

The rest is 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 the variable keystoreType, it is always null. What am I doing wrong?

+4
source share
1 answer

Spring cannot directly insert @Valueinto a static field.

you can either add the value of the value via the 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;
+7

All Articles