【问题标题】:How to read from application.properties如何从 application.properties 中读取
【发布时间】: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


【解决方案1】:

尝试像这样使用您的配置:

@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 之外的其他数据类型。

【讨论】:

  • 我想通过使用不同的'keys'动态读取application.properties
  • 所以您有想要解析的运行时计算键?否则,您可以根据需要通过键注入许多不同的属性。
  • 你能举个例子吗?
  • 我会修改上面的,通过注入显示不同的键。对于运行时计算的键,你可能想看看here
  • 你说你的环境实例为空。也许您尝试在自动装配发生之前访问实例(即调用 readProperty),如here 所述?
猜你喜欢
  • 2018-01-07
  • 1970-01-01
  • 2020-06-29
  • 2018-09-15
  • 1970-01-01
  • 2019-02-03
  • 1970-01-01
  • 2016-03-16
  • 2016-06-03
相关资源
最近更新 更多