zoukankan      html  css  js  c++  java
  • [Spring boot] Read values from external properties file

    Let's say we have a extral app.proporites file which contains some extra configuration:

    // resources/app.properties
    external.url="http://somedomain.com"

    We can read the extra propoties by using @Value("${xxx}")

    package com.example.in28minutes.properties;
    
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Component;
    
    @Component
    public class SomeExternalService {
    
        @Value("${external.url}")
        private String url;
    
        public String returnServiceURL () {
            return url;
        }
    }

    As you can see, we didn't define where should we looking for "app.proporties" file, this is what we should do in main file by @PropertySource("")

    package com.example.in28minutes;
    
    import com.example.in28minutes.properties.SomeExternalService;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.annotation.PropertySource;
    
    @SpringBootApplication
    @PropertySource("app.properties")
    public class In28minutesPropotiesApplication {
    
        private static Logger LOGGER = LoggerFactory.getLogger(In28minutesPropotiesApplication.class);
    
        public static void main(String[] args) {
            // Application Context
            ApplicationContext applicationContext =
                    SpringApplication.run(In28minutesPropotiesApplication.class, args);
            SomeExternalService someService = applicationContext.getBean(SomeExternalService.class);
    
            LOGGER.info("{}", someService.returnServiceURL());
        }
    }
  • 相关阅读:
    【面试】Java基础
    GC
    【面试】JVM
    Spooling技术
    数据结构之 平衡二叉树
    二叉树应用
    LINUX设备驱动模型之class
    RTC(x86)
    微内核和单内核
    Linux内核的五大模块
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10698096.html
Copyright © 2011-2022 走看看