java - 如何在 Spring Boot 的构造函数中读取 application.properties 值?

标签 java spring spring-boot environment-variables autowired

我知道构造函数在自动连接变量之前调用。但是,不幸的是,我想读取构造函数内的 application.properties 值?

@Component
public class DESedeEncryption {
  private static final String key = "TEST_KEY";
  public DESedeEncryption() {
    system.out.println(key);
 }
}

DESedeEncryption encrypted = new DESedeEncryption();

对于上面的类,在我的项目中总共有 108 个地方使用 new 运算符创建了对象。现在,我想从 application.properties 中读取该键值。但是,我需要使用 @Autowired 注释来更改所有 108 个位置。但是,有些将使用“new”运算符编写的对象创建放在实体类文件中。因此,我无法自动连接实体类内的对象。

请有人帮我解决这个问题。

最佳答案

您可以使用@Value注释在构造函数中声明一个变量,您想要在其中调用application.properties变量。

示例类:

  public DESedeEncryption(@Value("${key}") final String key) {
    system.out.println(key);
 }

关于java - 如何在 Spring Boot 的构造函数中读取 application.properties 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62488502/

相关文章:

Spring @Autowired 对象为空

java - 了解 spring mvc 中的 View 分辨率

java - Spring Boot jpa 与 H2 数据库

java - Android alarmManager,BroadcastReceiver onReceive 从未调用过

java - 使用 libgdx 对像素图进行着色

java - 为什么Spring任务调度程序不同时执行任务?

Spring 执行器 "/actuator"端点不可用

java - 如果使用 WebMvcConfigurationSupport 添加转换器,Swagger OpenAPI 3 不会在 springboot 2 上显示

java - 将数组从 A 类传递到 B 类

java - 延迟绑定(bind)二级类型参数