简体   繁体   English

在我的Springboot项目中,如何使用@Value注解获取Properties文件中的属性值

[英]In my Springboot project, how to use @Value annotation to get the property value in the Properties file

There are two classes and a configuration file, but they are all in the test directory I want to use the @Value annotation in class A to get the attribute value, and then assemble class A in class B, use the method in class A, I want to output the value obtained from the configuration file, but in fact it is all null How can i fix it!!! eg:有两个类和一个配置文件,但是都在test目录下 我想在class A中使用@Value注解获取属性值,然后在class B中组装class A,使用class A中的方法,我想output是从配置文件中获取的值,但实际上都是null 怎么修改!!! eg:

class structure: class结构:

班级结构

class A class 一个

A类

Class B Class乙

B类

properteis属性

属性

But if I turn Class A into a test class, I can get the results I want the result as follow但是如果我把 Class A 变成测试 class,我可以得到我想要的结果如下在 A 类上添加 @SpringBootTest

You need to autowire class A in class B .您需要在class B中自动装配class A Instead of using the spring managed bean with injected @Value you are creating a new class resulting in the variables in class A to be null.您不是使用带有注入@Value的 spring 托管 bean,而是创建一个新的 class,导致class A中的变量为 null。

@SpringBootTest
@Import(A.class)
public class B {

  @Autowire
  private final A a;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 是否可以使用springboot注释@Value从application.properties文件获取Map值 - Is it possible to get Map value from application.properties file using springboot annotation @Value 注释值未从 springboot properties.file 中读取 - Annotation value not reading from springboot properties.file 如何从属性文件导入值并在注释中使用它? - How to import value from properties file and use it in annotation? 将 Java 验证器用于带有 @Value 注释的 SpringBoot 属性 - Using Java validator for SpringBoot properties with @Value annotation 如何在PageFactory @FindBy注释中使用属性文件值? - How to use property file value in PageFactory @FindBy annotation? 使用@Value注解在Springboot中注入属性 - Injecting property in Springboot using @Value annotation 如何从 spring boot 项目的 application.properties 文件中获取属性值? - How to get property value from application.properties file on spring boot project? 如何将@value注解的值传递给SpringBoot中的controller - How to pass the value of an @value annotation to the controller in SpringBoot 将变量传递给@Value 注释以从属性文件中读取特定属性 - Passing a variable to @Value annotation for reading specific property from properties file Spring MVC:@Value注释获取* .properties文件中定义的int值 - Spring MVC: @Value annotation to get int value defined in *.properties file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM