Spring Boot: @Value returns always null

我与影子孤独终老i 提交于 2019-11-30 03:18:36

问题


I would like to use a value from application.properties file in order to pass it in the method in another class. The problem is that the value returns always NULL. What could be the problem? Thanks in advance.

application.properties

filesystem.directory=temp

FileSystem.java

@Value("${filesystem.directory}")
private static String directory;

回答1:


You can't use @Value on static variables. You'll have to either mark it as non static or have a look here at a way to inject values into static variables:

https://www.mkyong.com/spring/spring-inject-a-value-into-static-variables/

EDIT: Just in case the link breaks in the future. You can do this by making a non static setter for your static variable:

@Component
public class MyComponent {

    private static String directory;

    @Value("${filesystem.directory}")
    public void setDirectory(String value) {
        this.directory = value;
    }
}

The class needs to be a Spring bean though or else it won't be instantiated and the setter will be not be accessible by Spring.




回答2:


Few things for you to cross check apart from @Plog's answer.

static variables can't be injected with value. Check @Plog's answer.

  • Make sure the class is annotated with @Component or @Service
  • The component scan should scan the enclosing package for registering the beans. Check your XML if xml enabled configuration.
  • Check if the property file's path is correct or in classpath.



回答3:


The other answers are probably correct for the OP.

However, I ran into the same symptoms (@Value-annotated fields being null) but with a different underlying issue:

import com.google.api.client.util.Value;

Ensure that you are importing the correct @Value annotation class! Especially with the convenience of IDEs nowadays, this is a VERY easy mistake to make (I am using IntelliJ, and if you auto-import too quickly without reading WHAT you are auto-importing, you might waste a few hours like I did).

Of course, the correct class to import is:

import org.springframework.beans.factory.annotation.Value;



来源:https://stackoverflow.com/questions/46032748/spring-boot-value-returns-always-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!