Java 如何在spring boot中读取构造函数中的application.properties值?

Java 如何在spring boot中读取构造函数中的application.properties值?,java,spring,spring-boot,environment-variables,autowired,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 encrypt

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

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

DESedeEncryption encrypted = new DESedeEncryption();
对于上面的类,该对象是在我的项目中使用新操作符创建的,总共有108个位置。现在,我想从application.properties中读取该键值。但是,我需要使用@Autowired注释来更改所有108个位置。但是,有些应用程序将使用new运算符编写的对象创建放在实体类文件中。因此,我无法在实体类中自动连接对象


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

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

示例类:

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

您可以使用@Value annotation在构造函数中声明一个变量,您希望在其中调用application.properties变量

示例类:

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

我已经试过了。但是在创建对象时,我需要向构造函数传递哪个值呢?desedencryption encrypted=新的desedencryption;它给出了编译错误。您可以遵循一个选项,在构造函数中调用函数,该函数使用@Value注释从application.properties获取值并显示键值。希望此帮助。公共类EncryptionConfig{Value${app.encryption.key}私有字符串密钥;公共字符串getKey{return key;}}组件公共类desedencryption{Autowired private encryption config;public desedencryption{System.out.printlnconfig.getKey;}}}输出为null指针异常返回null。因为,新的加密。Config对象为空。请尝试此逻辑组件公共类DESedeEncryption{Value${app.encryption.key}私有字符串密钥;公共DESedeEncryption{System.out.printlngetKey;}公共字符串getKey{return key;}}我已经尝试过了。但是在创建对象时,我需要向构造函数传递哪个值呢?desedencryption encrypted=新的desedencryption;它给出了编译错误。您可以遵循一个选项,在构造函数中调用函数,该函数使用@Value注释从application.properties获取值并显示键值。希望此帮助。公共类EncryptionConfig{Value${app.encryption.key}私有字符串密钥;公共字符串getKey{return key;}}组件公共类desedencryption{Autowired private encryption config;public desedencryption{System.out.printlnconfig.getKey;}}}输出为null指针异常返回null。因为,新的加密。Config对象为空。请尝试此逻辑组件公共类DesedEncryption{Value${app.encryption.key}私有字符串密钥;公共DesedEncryption{System.out.printlngetKey;}公共字符串getKey{return key;}