Skip to main content

Reading Property Files in a Spring Framework in Java


Reading Property Files in a Spring Framework in Java


Of the many ways possible to achieve this in  a Java based Project, they can be classified into 2 categories based on the nature of configuration, namely Annotation Based and Xml based.

Annotation Based:


Use @PropertySource("classpath:fileName.properties")


@Configuration
@ComponentScan(basePackages = { "com.myproject.*" })
@PropertySource("classpath:dbConfig.properties")
public class GetDBConnection {

...
}


Read Property File Data using either Environment or @Value
  • METHOD 1 - Using Environment:

@Autowired
private Environment env;


String dbUrl = env.getProperty("db.url");
  • Using @Value

@Value("${db.url}") // To be bound with an attribute
private String dbUrl;


//To resolve ${} in @Value, use PropertySourcesPlaceholderConfigurer.

@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
        return new PropertySourcesPlaceholderConfigurer();
}



 XML Based:


Using Spring Utils: (To Be Updated)








Comments