How to read data from java properties file using Spring Boot

前端 未结 4 1428
青春惊慌失措
青春惊慌失措 2020-12-01 07:30

I have a spring boot application and I want to read some variable from my application.properties file. In fact below codes do that. But I think there is a good

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-01 08:30

    You can use @PropertySource to externalize your configuration to a properties file. There is number of way to do get properties:

    1. Assign the property values to fields by using @Value with PropertySourcesPlaceholderConfigurer to resolve ${} in @Value:

    @Configuration
    @PropertySource("file:config.properties")
    public class ApplicationConfiguration {
    
        @Value("${gMapReportUrl}")
        private String gMapReportUrl;
    
        @Bean
        public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
            return new PropertySourcesPlaceholderConfigurer();
        }
    
    }
    

    2. Get the property values by using Environment:

    @Configuration
    @PropertySource("file:config.properties")
    public class ApplicationConfiguration {
    
        @Autowired
        private Environment env;
    
        public void foo() {
            env.getProperty("gMapReportUrl");
        }
    
    }
    

    Hope this can help

提交回复
热议问题