Braj
Braj

Reputation: 91

How to read application.properties file without Environment

Please can you help me to read the properties from application.properties file in Spring Boot, without autowiring the Environment and without using the Environment?

No need to use ${propname} either. I can create properties object but have to pass my properties file path. I want to get my prop file from another location.

Upvotes: 6

Views: 38981

Answers (7)

Supercoder
Supercoder

Reputation: 1204

The following code extracts the environment value from an existing application.properties file which is located in the Deployed Resources under WEB-INF/classes :

    // Define classes path from application.properties :
    String environment;
    InputStream inputStream;
    try {
        // Class path is found under WEB-INF/classes
        Properties prop = new Properties();
        String propFileName = "com/example/project/application.properties";

        inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
        // read the file
        if (inputStream != null) {
            prop.load(inputStream);
        } else {
            throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
        }

        // get the property value and print it out
        environment = prop.getProperty("environment");

        System.out.println("The environment is " + environment);
    } catch (Exception e) {
        System.out.println("Exception: " + e);
    }

Here is example, running the above code with the following input from the application.properties (Text file):

# Application settings file
environment=Test
release_date=DATE
session_timeout_minutes=25
## Allowable image types
img_file_extensions="jpeg;pjpeg;jpg;png;gif"
## Images are saved with this extension
img_default_extension=jpg
# Mail Settings / Addresses
mail_debug=false
Output:

The environment is Test

Upvotes: 2

Adding to Vladislav Kysliy's elegant solution, below code can be directly plugged as REST API Call to get all the key/value of application.properties file in Spring Boot without knowing any key. Additionally, If you know the Key you can always use @Value annotation to find the value.

@GetMapping
@RequestMapping("/env")
public java.util.Set<Map.Entry<Object,Object>> getAppPropFileContent(){
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    java.util.Properties properties = new java.util.Properties();
    try(InputStream resourceStream = loader.getResourceAsStream("application.properties")){
        properties.load(resourceStream);
    }catch(IOException e){
        e.printStackTrace();
    }
    return properties.entrySet();
}

Upvotes: 0

Abbin Varghese
Abbin Varghese

Reputation: 2774

If everything else is properly set, you can the annotation @Value. Springboot will take care of loading the value from property file.

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

@Configuration
@PropertySource("classpath:/other.properties")
public class ClassName {
  @Value("${key.name}")
  private String name;
}

Upvotes: 1

Vladislav Kysliy
Vladislav Kysliy

Reputation: 3736

OrangeDog solution didn't work for me. It generated NullPointerException.

I've found another solution:

ClassLoader loader = Thread.currentThread().getContextClassLoader();
Properties properties = new Properties();
try (InputStream resourceStream = loader.getResourceAsStream("application.properties")) {
    properties.load(resourceStream);
} catch (IOException e) {
    e.printStackTrace();
}

Upvotes: 15

Smaniotto
Smaniotto

Reputation: 454

To read application.properties just add this annotation to your class:

@ConfigurationProperties
public class Foo { 
}

If you want to change the default file

@PropertySource("your properties path here")
public class Foo { 
}

Upvotes: 1

Bohdan Levchenko
Bohdan Levchenko

Reputation: 3561

Try to use plain old Properties.

final Properties properties = new Properties();
properties.load(new FileInputStream("/path/config.properties"));
System.out.println(properties.getProperty("server.port"));

In case you need to use that external properties file in your configuration it can be accomplished with @PropertySource("/path/config.properties")

Upvotes: 2

OrangeDog
OrangeDog

Reputation: 38777

This is a core Java feature. You don't have to use any Spring or Spring Boot features if you don't want to.

Properties properties = new Properties();
try (InputStream is = getClass().getResourceAsStream("application.properties")) {
  properties.load(is);
}

JavaDoc: http://docs.oracle.com/javase/8/docs/api/java/util/Properties.html

Upvotes: 17

Related Questions