How to get the content of file properties in Spring Boot?

Solution 1:

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