【发布时间】:2018-05-18 20:07:23
【问题描述】:
我正在尝试从 application.properties 中读取,但无法正常工作。
这是我的代码:
package config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
@Configuration
@PropertySource("classpath:application.properties")
public class PropertiesReader {
@Autowired
private Environment env;
public String readProperty(String key) {
return env.getProperty(key);
}
}
这是我调用 readProperty 的地方:
public class JwtSettings {
public String key;
public long expiration;
//The JWT signature algorithm we will be using to sign the token
public SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
public JwtSettings() {
PropertiesReader propertiesReader = new PropertiesReader();
key = propertiesReader.readProperty(ApplicationProperties.JWT_KEY.key);
}
当我运行此代码时,env 实例为空。 我的 application.properties 文件位于资源文件夹中。 我没有想法,请帮忙。
【问题讨论】:
-
你想多了。 Spring Boot 已经读取了
application.properties你不需要再做一次。 -
所以你说我需要删除 '@PropertySource("classpath:application.properties")' 注释?
-
是的,如果您需要属性,只需使用
@Value注入它们或绑定到自定义属性对象(所有这些都在 Spring Boot 参考指南中进行了解释)。 -
我的 env 实例仍然为空
-
然后你自己创建一个实例,而不是让 Spring 创建一个并注入它。
标签: java spring spring-boot