Saturday, September 18, 2021

How to load data from properties file?

 We need to store data using a key in property file .Then use @Value annotation over a variable which will hold that data .Then we should use another @PropertySource annotation is used to provide properties file into spring environment .

Ex:

Suppose we have a url in app.properties file as

external.service.url = http://helloworld.com/hello


Now we have a service class which will provide this url .

@Component

public class ExternalService{

       @Value("${external.service.url}") 

       private String url;

        public String getUrl(){

        return url;

        }

}


Now we want to load properties file while load the class, then

@Configuration 

@ComponentScan

@PropertySource("classpath:app.properties")

public class SpringFrameworkProperties{

  public void main(String[] args){

  AnnotationConfigApplicationContext context = new         AnnotationConfigApplicationContext(SpringFrameworkProperties.class);

   ExternalService service= context.getBean(ExternalService.class);

System.out.println(service.getUrl());

  }

}

No comments:

Post a Comment

Fluent interface pattern

 public class UserConfigurationManager {     private String userName;     private String password;     private UserConfigurationManager() { ...