Inject Primitive and String Type
1. Application Properties
- Always configuring data which is commonly being used by all spring Beans.
- Called as Configuration file.
- key value pair format(key-val).
- two types of properties
- pre-defiend(spring.application.name)
- used defiend(db.name=alamgir)
Example application.properties file:
spring.application.name=b-dependency-injection
db.port=8080
db.url=localhost:8080
db.password=mysql
db.database=mysql,oracle,postgres
2. Using @Value Annotation
Injecting values directly:
Injecting from properties:
Default Values
If the property is missing, the default valuemysql will be used.
Injecting Multiple Values
For list-type properties:
If db.database=mysql,oracle,postgres : it becomes a list: [mysql, oracle, postgres]
How it works:
- Spring checks
application.properties(orapplication.yml). - Looks for the property.
- If Found : proceeds.
- If Not found : throws
java.lang.IllegalArgumentException: Could not resolve placeholder 'db.password'.
- Injects the value into the field.
3. Using @PropertySource
Add external .properties files:
Key Points
@PropertySourcetells Spring where to load a.propertiesfile from.- Used on a @Configuration class.
- Works with
@Value("${property.name}"). - Can load multiple files:
classpath:looks insidesrc/main/resources. -
If a property exists in both
application.propertiesand a@PropertySourcefile:- Spring Boot uses the value from application.properties.
@PropertySourcehas lower priority than default Spring Boot property files.
Github Code : Inject primitives and String type : Spring Boot