Property Placeholder & Profiles
In real applications, configuration often changes between environments (dev, test, prod). You don't want to hardcode database URLs or credentials. Spring provides two powerful features: property placeholders and profiles.
Property Placeholders allow you to externalize configuration into
.properties files and refer to them using ${...} syntax.db.url=jdbc:mysql://localhost:3306/mydb
db.username=root
db.password=secret
<context:property-placeholder location="classpath:database.properties"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="url" value="${db.url}"/>
<property name="username" value="${db.username}"/>
<property name="password" value="${db.password}"/>
</bean>
Spring Profiles let you define different sets of beans for different environments. For example, you might use an in‑memory database for testing and a real one for production.
@Configuration
public class DataSourceConfig {
@Bean
@Profile("dev")
public DataSource devDataSource() {
return new EmbeddedDatabaseBuilder().build();
}
@Bean
@Profile("prod")
public DataSource prodDataSource() {
return DataSourceBuilder.create().build();
}
}
You can activate a profile by setting
spring.profiles.active system property or programmatically.Two Minute Drill
- Property placeholders (
${...}) externalize configuration into.propertiesfiles. - Use
<context:property-placeholder>or@PropertySourceto load properties. - Profiles allow different bean definitions for different environments.
- Annotate beans with
@Profileand activate profiles viaspring.profiles.active.
Need more clarification?
Drop us an email at career@quipoinfotech.com
