Spring Boot中如何获取文件属性的内容 [英] How to get the content of file properties in Spring Boot
问题描述
作为标题,我的自定义属性:
As the title, my custom properties:
#app settings
my.chassisNum=10
java代码:
@PropertySource("classpath:appconf.properties")
@ConfigurationProperties(prefix = "my" )
@Component
public class AppConfig {
private String chassisNum;
public String getChassisNum() {
return this.chassisNum;
}
public void setChassisNum(String chassisNum) {
this.chassisNum = chassisNum;
}
}
当 Spring Boot 启动完成时,我得到的chassisNum"值为 10.当我在 spring-boot 未启动完成时在其他地方得到它时,它得到null"
when Spring Boot start completed, I got the "chassisNum" value is 10. when I got it in other place when spring-boot not start completed, it get "null"
@Component
public class CreateBaseFolder {
private final Logger logger = LogManager.getLogger(CreateBaseFolder.class);
private File f;
@Autowired
AppConfig appconf;
public CreateBaseFolder() {
System.out.println(appconf.getChassisNum());
}
我尝试了很多方法来获取它的价值,但都是错误的.例如:implements InitializingBean、@DependsOn....
i try many way to get it value,but is false.such as :implements InitializingBean, @DependsOn....
推荐答案
假设你有 application.properties
内容:
foo.bar=Jerry
您将使用注释 @Value
package com.example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class GetPropertiesBean {
private final String foo;
@Autowired
public GetPropertiesBean(@Value("${foo.bar}") String foo) {
this.foo = foo;
System.out.println(foo);
}
}
当然,我们需要一个入口点:
Of course, we need an entry point:
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
然后将类应用程序作为 Spring Boot 应用程序运行,组件是自动加载的,您将在控制台屏幕上看到结果:
Then run class Application as Spring Boot application, component is autoload, you will see result at console screen:
杰瑞
这篇关于Spring Boot中如何获取文件属性的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!