如何从Springboot的属性文件中读取它

问题描述

application.properties文件具有:

my.greeting = Hello

ServiceClass文件具有:

@Value("${my.greeting}")
private String messageFromProperties;

MainAppfile:

public static void main(String[] args) {
        SpringApplication.run(SpringBootApplicationConceptsApplication.class,args);
        ServiceClass serv = new ServiceClass();`enter code here`
        System.out.println(serv.getMessageFromProperties());//getting null
    }

请让我知道我在这里想念的是什么。所有配置都在等待中

解决方法

您需要使用@PropertySource来指定来源。 例如:

@PropertySource(value = "example.properties")

您可以在主类中使用上述注释。 例如:

@SpringBootApplication
@PropertySource(value = "example.properties")
public class ExampleApplication {
    public static void main(String[] args) {
        SpringApplication.run(ExampleApplication.class,args);
    }
}

或者,您可以将它们与以@Configuration注释的类一起使用。 例如:

@Configuration
@PropertySource("example.properties")
public class ExampleConfiguration {
    //code
}

如果这没有帮助,我建议您与他人共享完整的代码,以了解问题的确切原因。