Spring Boot 读取配置文件内容的方法(application.properties)

springboot 中的配置通常放在application.properties中,读取的方法有以下三种

方法一、Environment

可以通过Environment的getProperty方法来获取想要的配置信息,代码例子如下

@RestController
public class HelloController{


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

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

        }


}

方法二、@Value

可以注入配置的信息

@RestController
public class HelloController{


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

        @GetMapping("/hello")
        public String hello(){

         return port;

        }


}

方法三、自定义配置类

(1)prefix定义配置的前缀

@ConfigurationProperties(prefux="com.cxytiandi")
@Component
public class MyConfig{

    private String name;

    public String getName(){
         return name;
    }

    public void setName(String name){
         this.name=name;
    }

}

(2)读取配置的方法如下

@RestController
public class HelloController{

        //注入对象
        @Autowired
        private MyConfig myConfig;

        @GetMapping("/hello")
        public String hello(){
           return myConfig.getName;
        }
}

(3)注意:此时在application.properties中的定义如下

com.cxytiandi.name=yinjihuan

 

你可能感兴趣的:(spring,boot)