SpringBoot读取配置文件配置信息

第一:通过Environment

        通过Environment的getProperty()方法获配置信息,其中server.port就是指配置文件中的配置key

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ResourceController {

    //注入对象
    @Autowired
    private Environment environment;

    @GetMapping("/hello")
    public String hello(){
        //读取配置
        String port = environment.getProperty("server.port");
        System.out.println(port);
        return port;

    }

}

第二种:通过@Value注入具体的配置信息

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ResourceController {

    //注入对象
    @Value("${server.port}")
    private String port;

    @GetMapping("/hello")
    public String hello() {
        //读取配置
        System.out.println(port);
        return port;

    }

}