'Is it necessary to use Commons Configuration to use @PropertySource in Spring 5.x?

I am unable to load property file in resources directory,

@Configuration
@PropertySource(value = "classpath:/test.properties", ignoreResourceNotFound = true)
public class ArgConfig {

    @Autowired
    private Environment env;

    @Value("${store.name}")
    private String name;

    public String getName() {
        return name;
    }

}

test.properties contains --> store.name=nike

Property Source from Spring Documentation

Followed the same from the documentation still unable to load the properties file.



Solution 1:[1]

Apologies for wasting precious time.

I found the answer, it is just to place the property file under resource directory(which I did even before but not sure why it thrown error).

Here is the entire code, Project structure: enter image description here

@RestController
@RequestMapping("/")
public class SampleRestController {

    @Autowired
    private Store storeDetails;

    @GetMapping("/names")
    public List<String> getNames(){
        String storeName = storeDetails.getName();
        System.out.println("Store Name = " + storeName);
        return storeName!=null ? Arrays.asList(storeName) : Arrays.asList("store1","store2","store3");
    }
}

@Configuration
@PropertySource("classpath:/store.properties")
public class StoreConfig {
    @Autowired
    Environment env;

    @Bean
    public Store storeDetails() {
        Store store = new Store();
        store.setName(env.getProperty("store.name"));
        return store;
    }
}

@Component
public class Store {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

@SpringBootApplication
public class SpringbootApplication {

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

}

Thanks everyone!!!

Solution 2:[2]

Is it mandatory for you to use it as test.properties? if so, use the @PropertySource annotation. Otherwise, use it like application-test.properties and set the profile as test using @ActiveProfiles("test")

Another way is, place your application.properties under src/test/resources if you want to override the value.

Refer https://www.baeldung.com/spring-tests-override-properties for more information

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 sathishkraj
Solution 2 Shakthi