我的 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/