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?
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;
对于在所有上述建议之后仍然面临问题的人,请确保在按照本答案中所述构造 bean 之前您没有访问该变量。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.