Rama Krishna. G
Rama Krishna. G

Reputation: 536

How to load external file using ClassPathResource in Spring?

We have one file on one drive (C:\megzs\realm.properties). We would like to load this file and read the content using the ClassPathResource available in Spring. But we see the file is not found exception. The code we are trying is

Resource resource = new ClassPathResource("file:c:/megzs/realm.properties");
Properties prop = PropertiesLoaderUtils.loadProperties(resource);

Here we are using ClassPathResource to load external file. Can ClassPathResource load the external file ?
And How can we load mutiple properties files (one from classpath and another from absolute path) ??

Upvotes: 4

Views: 10753

Answers (2)

codingmonkey
codingmonkey

Reputation: 1406

if you want to access file based resource use FileSystemResource and provide it to PropertiesLoaderUtils.loadProperties() method. Below code reads property file from file system if not exists, it will load it from the classpath. hope it helps.

    public static Properties getProperties(String propertyFile) {
    try {
        Resource resource = new FileSystemResource(propertyFile);
        if (!resource.exists()) {
            resource = new ClassPathResource(propertyFile);
        }
        return PropertiesLoaderUtils.loadProperties(resource);
    } catch (Exception ignored) {
        return null;
    }
}

Upvotes: 7

Priyamal
Priyamal

Reputation: 2989

im loading many properties using @PropertySource() and properties will be read using Environment object may be you should try with this approach you approach is not wrong bt it is somewhat confusing to me

@Configuration
    @PropertySource({
        "classpath:config.properties",
        "file:/path/to/application.properties" //if same key, this will 'win'
    })
    public class AppConfig {

        @Autowired
        Environment env;

                public void ReadProperties() {

        String property1 = env.getProperty("property");
        String property2 = env.getProperty("property2");
                }

                //if theres same key found in the second property 
                //file key in the second property file wiil be read
    }

Upvotes: 0

Related Questions