java-Spring@Value注释返回null
我试图利用java-Spring@Value注释返回null,java,spring,Java,Spring,我试图利用@Value注释,从属性文件中自动填充字符串变量,但运气不好。未设置值,值为null 以下是我的配置: SendMessageController.java @RestController public class SendMessageController { @Value("${client.keystore.type}") private static String keystoreType; @RequestMapping(value = "/sen
@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) {
.......
}
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>
当我运行应用程序并尝试访问keystoreType
变量时,它总是null
。
我做错了什么?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;
致:
对于那些在所有上述建议之后仍然面临问题的人,请确保在按照本文所述构造bean之前,您没有访问该变量。您能否确保
@Value
注释的导入语句是import org.springframework.beans.factory.annotation.Value代码>?Spring不处理静态任何内容。为什么字段是静态的
?好的,在使变量非静态后,一切正常。谢谢。谢谢你的解释,这解决了问题!等待超时:)@RafikBELDI这东西对我不起作用。我从另一个类调用静态方法,该类具有静态变量。
@Value("${client.keystore.type}")
private static String keystoreType;
@Value("${client.keystore.type}")
private String keystoreType;