Spring Boot中如何获取文件属性的内容

A_W*_*Wen 4 spring-boot

作为标题,我的自定义属性:

#app settings
my.chassisNum=10
Run Code Online (Sandbox Code Playgroud)

代码:

@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;
    }
}
Run Code Online (Sandbox Code Playgroud)

当 Spring Boot 启动完成时,我得到的“chassisNum”值为 10。当我在 spring-boot 未启动完成时在其他地方得到它时,它得到“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());


    } 
Run Code Online (Sandbox Code Playgroud)

我尝试了很多方法来获取它的价值,但都是错误的。例如:实现 InitializingBean、@DependsOn ....

nhu*_*uvy 7

假设你有application.properties内容:

foo.bar=Jerry
Run Code Online (Sandbox Code Playgroud)

您将使用注释 @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);
    }

}
Run Code Online (Sandbox Code Playgroud)

当然,我们需要一个入口点:

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);
    }

}
Run Code Online (Sandbox Code Playgroud)

然后将类 Application 作为 Spring Boot 应用程序运行,组件是自动加载的,您将在控制台屏幕上看到结果:

杰瑞

在此处输入图片说明