Spring Boot @Value Properties

后端 未结 8 1204
刺人心
刺人心 2020-12-10 10:05

I have a Spring Boot application and in one of the classes, I try to reference a property from the application.properties file using @Value. But, the property d

8条回答
  •  难免孤独
    2020-12-10 10:38

    To read the values from application.properties we need to just annotate our main class with @SpringBootApplication and the class where you are reading with @Component or variety of it. Below is the sample where I have read the values from application.properties and it is working fine when web service is invoked. If you deploy the same code as is and try to access from http://localhost:8080/hello you will get the value you have stored in application.properties for the key message.

    package com.example;
    
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @SpringBootApplication
    @RestController
    public class DemoApplication {
    
        @Value("${message}")
        private String message;
    
        public static void main(String[] args) {
            SpringApplication.run(DemoApplication.class, args);
        }
    
        @RequestMapping("/hello")
        String home() {
            return message;
        }
    
    }
    

    Try and let me know

提交回复
热议问题