java - 无法使用@value 或使用自动连接到环境从属性文件中读取值

标签 java spring spring-boot oop dependency-injection

我的 Spring boot 项目中有两个属性文件。而且我能够在一个类中读取两者的属性。但是当我尝试使用 @Value 或通过 Autowired Environment 从不同的类读取相同的值时,它给了我 null。

    prop.name=test /*   property file value */

    @Component
    public class TestUtil { // This is the class giving me null value

        @Value("${prop.name}")
        String st;

        public String getTestString()
        {
            System.out.println(st+ " ***");
            return st;

        }
    }

//Using @Autowired Enviroment
public class TestUtil {

    @Autowired
    private Environment env;


    public String getTestString()
    {
        System.out.println(env.getProperty("prop.name")+ " ***");
        return env.getProperty("prop.name");

    }
}

/* Class below giving me value from properties file*/

        public class JsonWriter extends JsonResponseWriter {

        @Value("${prop.name}")
        private String contentsMenus;

      /* Some method*/
       System.err.println("from JsonWriter  "+contentsMenus);

这里是 Autowiring

@Service
public class ResponseUtil {
    @Autowired
     private TestUtil util ;

在上面的类中我使用的是 Autowiring

最佳答案

您在 Value 注释中缺少美元符号。这应该可以完成工作:

@Value("${prop.name}")

关于java - 无法使用@value 或使用自动连接到环境从属性文件中读取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55684109/

相关文章:

java - 为什么通过 Ghostscript API 渲染图像需要这么长时间?

java - Spring Security 问题 - 404 错误

spring - 使用 Spring Boot 1.4.1 和 H2 测试 JPA

java - Reactjs推荐的部署方式

spring-data-jpa - Spring boot + Spring Data JPA + Atomikos + 多数据库配置

Spring Boot 1.4 -> 1.5 突然检查主机名

java - 将自定义属性添加到 JTree 并打印它

java - 如何参数化Dockerfile?

java - 如何为mybatis框架生成的mapper类创建Aspect?

java - 启动 swing 应用程序的最佳实践