Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the content of file properties in Spring Boot

Tags:

spring-boot

As the title, my custom properties:

#app settings
my.chassisNum=10

java code:

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

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


    } 

i try many way to get it value,but is false.such as :implements InitializingBean, @DependsOn....

like image 799
A_Wen Avatar asked May 08 '17 09:05

A_Wen


1 Answers

Assume you has application.properties with content:

foo.bar=Jerry

You will use annotation @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);
    }

}

Then run class Application as Spring Boot application, component is autoload, you will see result at console screen

Jerry

enter image description here

like image 76
Do Nhu Vy Avatar answered Oct 01 '22 05:10

Do Nhu Vy