Skip to content

Instantly share code, notes, and snippets.

@bluearth
Created February 8, 2024 00:16
Show Gist options
  • Save bluearth/8ec0bf6cc4a18fd32b10cad9c892266c to your computer and use it in GitHub Desktop.
Save bluearth/8ec0bf6cc4a18fd32b10cad9c892266c to your computer and use it in GitHub Desktop.

#spring [#spring-boot]{}

Question

Property files, how do they work in Spring?

Answer

If a bean class is annotated with @PropertySource, when Spring is conjuring this bean Spring will also loads property file it defines.

Then Spring will make the keys in that property file available for injection into your bean classes using the @Value annotation.

@Component
@PropertySource("classpath:myproperty.properties")
public class MyBean {
  
  @Value("myproperty.value1")
  String value1;
  
  @Value("myproperty.value2")
  String value2;  
  
}

In the example above, when Spring is conjuring beans of type MyBean, it will also loads myproperty.properties property file from the classpath. Then the values in there will be made available for all routes of injection.

Spring will fail to conjure the bean if the property file cannot be found. If you want spring to continue even if the file cannot be found, you can use this attribute:

@PropertySource(value = "classpath:some.properties", ignoreResourceNotFound = true)
public class MyBean {
//...
}

As we can see from the example above, Spring is able to covert the values into their primitive java types (e.g. int becomes int, string becomes string, etc) even into their compound array types

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment