Home > Blockchain >  Is it necessary to use Commons Configuration to use @PropertySource in Spring 5.x?
Is it necessary to use Commons Configuration to use @PropertySource in Spring 5.x?

Time:04-22

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

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!!!

  • Related