java - Spring @Value注释返回null

时间:2016-04-10 18:50:39

标签: java spring

我正在尝试利用@Value注释并从属性文件中自动填充我的字符串变量,但没有运气。值未设置且为null

这是我的配置:

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

其余-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>

当我运行我的应用程序并尝试访问keystoreType变量时,它总是null。 我做错了什么?

2 个答案:

答案 0 :(得分:8)

Spring无法直接将@Value注入静态字段。

您可以通过带注释的setter添加注入值,如下所示:

private static String keystoreType;

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

或改变:

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

到:

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

答案 1 :(得分:0)

对于经过上述所有建议后仍面临问题的人,请确保在按照本answer中所述构造bean之前,不要访问该变量。