![](/img/trans.png)
[英]How to read variable from application.properties from method that is testing
[英]How to read from application.properties
我正在尝试从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实例为null。 我的application.properties文件位于资源文件夹中。 我没有主意,请帮忙。
尝试像这样使用您的配置:
@Service
public class JwtSettings {
private String key;
private long expiration;
//The JWT signature algorithm we will be using to sign the token
public SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
@Autowired
public JwtSettings(PropertiesReader propertiesReader) {
this.key = propertiesReader.readProperty(ApplicationProperties.JWT_KEY.key);
}
}
您永远不要自己实例化Spring托管组件(通过在代码中调用构造函数)。 相反,您应该通过@Autowired
使用Spring Dependency-Injection来确保正确解析了所有依赖项。
要使用Spring注入属性(通常):
如果尝试从属性资源访问属性值,请尝试使用Springs @Value
注释将其注入。
您的application.properties可能看起来像:
myproperty.test1=mytestvalue
myproperty.test2=123
现在,您有了一个Spring组件,您想在其中使用属性值,然后像这样注入它们:
@Component
private class MyTestComponent {
@Value("${myproperty.test1:mydefaultvalue}")
private String test1Value;
@Value("${myproperty.test2:-1}")
private int test2Value;
}
当然,您可以为属性使用String以外的其他数据类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.