Springboot adds configuration file reading outside of application.properties

         In the process of developing SpringBoot projects, we sometimes need to provide our own defined configuration files such as applicationDynamic.properties in order to distinguish it from the default configuration provided by the application.properties configuration file. Here I introduce how to read the custom configuration file. The SpringBoot version uses 1.5.6.RELEASE.

  1. Define a custom configuration file applicationDynamic.properties, and its path is also placed in the config directory:

#Used for url dynamic loading location
file.uPath=file:f:\\testDynamicBean-1.0-SNAPSHOT.jar
#Used to get the loading location by way of JarFile
file.fPath=f:\\testDynamicBean-1.0-SNAPSHOT.jar
#class class for loading
file.className=com.dynamic.DynamicBean3

     2. Define a java class for reading configuration files

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

/**
 * @version 1.0 2017/8/15
 * @description configure the specified properties file
 */
@Configuration
@ConfigurationProperties
@PropertySource("classpath:config/applicationDynamic.properties")
public class DynamicSetting {
    @Value("${file.fPath}")
    private String fPath;
    @Value("${file.className}")
    private String className;
    @Value("${file.uPath}")
    private String uPath;

    public String getfPath() {
        return fPath;
    }

    public void setfPath(String fPath) {
        this.fPath = fPath;
    }

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }

    public String getuPath() {
        return uPath;
    }

    public void setuPath(String uPath) {
        this.uPath = uPath;
    }
}

     3. Define the App.java startup class:

     

import com.springRedis.config.DynamicSetting;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

/**
 * @version 1.0 2017/7/31
 * @description
 */
@SpringBootApplication
@EnableConfigurationProperties({DynamicSetting.class})
public class App {

    public static void main(String [] args){
        SpringApplication.run(App.class);
    }

}

    Through the above steps, we can call the DynamicSetting.java class in other classes through atuowired injection to use the property values.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327017273&siteId=291194637