Java Spring Boot读取application.properties/.yml变量,不带注释
我想用new操作符创建一个类,在这个类中,我想从application.yml文件中读取一个属性,在SpringBoot应用程序中如何做到这一点Java Spring Boot读取application.properties/.yml变量,不带注释,java,spring,spring-boot,Java,Spring,Spring Boot,我想用new操作符创建一个类,在这个类中,我想从application.yml文件中读取一个属性,在SpringBoot应用程序中如何做到这一点 换句话说,我不能使用@Value、@Autowire、@Component注释。您需要这样做: @Configuration @ConfigurationProperties(prefix = "test") public class TestProperties{ private String testProperty1; publ
换句话说,我不能使用@Value、@Autowire、@Component注释。您需要这样做:
@Configuration
@ConfigurationProperties(prefix = "test")
public class TestProperties{
private String testProperty1;
public String getTestProperty1() {
return testProperty1;
}
public void setTestProperty1(String testProperty1) {
this.testProperty1= testProperty1;
}
}
下一步,在application.properties中:
test.testPropety1 = yourProperty
由于@Configuration注释,您可以将这个属性类实现为bean。希望这对您的问题有所帮助:)那么,当我在某些方法中执行TestProperties t=new TestProperties()时,我将填充t.TestProperty1?在我的方法结束后,这个t变量会被垃圾收集吗?在构造函数中传递这个类。然后,您将使用application.properties中的数据填充所有属性。但正如我所记得的,“new”关键字也可以工作。是的,当您在没有构造函数或“new”关键字的类中使用它时,它将为null。这里有关于使用Spring的JVM GC的信息: