48

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 method for this alternative.

Properties prop = new Properties();
InputStream input = null;

try {
    input = new FileInputStream("config.properties");
    prop.load(input);
    gMapReportUrl = prop.getProperty("gMapReportUrl");
} catch (IOException ex) {
    ex.printStackTrace();
} finally {
    ...
}

5 Answers 5

59

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

Sign up to request clarification or add additional context in comments.

4 Comments

Why foo void? How to use this class?
@gstackoverflow It is just an example. You can use it as you like.
getting FileNotfoundException, but my file is in the resources folder res/sensitive.properties
@PropertySource() is optional. Just in case anyone needs this information
17

i would suggest the following way:

@PropertySource(ignoreResourceNotFound = true, value = "classpath:otherprops.properties")
@Controller
public class ClassA {
    @Value("${myName}")
    private String name;

    @RequestMapping(value = "/xyz")
    @ResponseBody
    public void getName(){
        System.out.println(name);
    }
}

Here your new properties file name is "otherprops.properties" and the property name is "myName". This is the simplest implementation to access properties file in spring boot version 1.5.8.

5 Comments

I have "sensitive.properties" inside the resources folder, have used the above approach with @Configuration annotation, but it is not able to read value.
@Girish please check the location of your properties file. In the above approach, the properties file was in the same location with the application.properties file
I also have it in the resources folder, but Environment is null and propertysource also not working
@Girish this should work actually. please check typographical errors.
If property file is inside App->src/main/resource/config/app-config.properties i.e. after class path inside some directory then use this : @PropertySource(ignoreResourceNotFound = true, value="classpath:config/app-config.properties")
16

I have created following class

ConfigUtility.java

@Configuration
public class ConfigUtility {

    @Autowired
    private Environment env;

    public String getProperty(String pPropertyKey) {
        return env.getProperty(pPropertyKey);
    }
} 

and called as follow to get application.properties value

myclass.java

@Autowired
private ConfigUtility configUtil;

public AppResponse getDetails() {

  AppResponse response = new AppResponse();
    String email = configUtil.getProperty("emailid");
    return response;        
}

application.properties

[email protected]

unit tested, working as expected...

1 Comment

I notice you don't specify a property file name? Does this just load all *.properties files in the classpath?
0

For those of you who want to expose every property from either a .properties or .yml file, Spring Boot automatically creates an endpoint that does just that: endpoint /actuator/env. It is disabled by default though. To enable it, be sure to include env in the application property below: management.endpoints.web.exposure.include=env

You can then filter the properties that you want to keep in the program that reads the endpoint.

Comments

-1
public class Properties {
private static java.util.Properties propsExported = new java.util.Properties();

// Load properties from the "error.properties" file
static {
    try (InputStream inputStream = Properties.class.getClassLoader().getResourceAsStream("error.properties")) {
        if (inputStream == null) {
            throw new IOException("Properties file 'error.properties' not found on the classpath");
        }
        propsExported.load(inputStream);
    } catch ( IOException e) {
        // Log or handle the error as appropriate
        e.printStackTrace();
    }
}

public static String getProperty(final String key) {
    String value = propsExported.getProperty(key);
    return value;
}

}

public static void main(String[] args) {
    String errorCode = Properties.getProperty("request.id.required");
    String errorMessage = Properties.getProperty(errorCode);
    System.out.println("errorCode: "+errorCode);
    System.out.println("errorMessage: "+errorMessage);
}

1 Comment

Naming your class Properties may be a bit confusing, no? Also, why is your file named error.properties when the question states that the file name is application.properties?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.