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

AMA*_*ESH 2 java spring environment-variables autowired spring-boot

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

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

DESedeEncryption encrypted = new DESedeEncryption();
Run Code Online (Sandbox Code Playgroud)

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

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

小智 6

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

示例类:

  public DESedeEncryption(@Value("${key}") final String key) {
    system.out.println(key);
 }
Run Code Online (Sandbox Code Playgroud)