@PropertySource and @Value in Spring

@PropertySource provides a convenient and declarative mechanism for adding a PropertySource to Spring’s Environment. This is used in conjunction with @Configuration classes.

Let’s see how we can use it.

Project Structure

Screen Shot 2020-02-28 at 10.26.28 PM

database.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/testschema
dbuser=root
dbpassword=root
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true

 

In the below Config class, we are creating the dataSource bean by reading the DB properties in database.properties using @PropertySource annotation.

We can inject Environment to get the property values or use @Value to read the specific property from the properties file.

AppConfig.java

package com.spring.datajpa.config;

import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
@Configuration
@PropertySource(“classpath:database.properties”)
public class AppConfig {
@Autowired
Environment environment;
@Value(“${url}”)
private String dbUrl;
private final String URL = “url”;
private final String USER = “dbuser”;
private final String DRIVER = “driver”;
private final String PASSWORD = “dbpassword”;
@Bean
DataSource dataSource() {
DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
driverManagerDataSource.setUrl(environment.getProperty(URL));
driverManagerDataSource.setUsername(environment.getProperty(USER));
driverManagerDataSource.setPassword(environment.getProperty(PASSWORD));
driverManagerDataSource.setDriverClassName(environment.getProperty(DRIVER);
return driverManagerDataSource;
}
}
@PropertySources
We can use @PropertySources to read multiple properties files.
@PropertySources({
@PropertySource(“classpath:database.properties”),
@PropertySource(“classpath:database1.properties”)})
public class AppConfig {
}
ignoreResourceNotFound
ignoreResourceNotFound was introduced in Spring 4.0.
ignoreResourceNotFound = true
If that resource or property file is not available in the classpath, it does not throw FileNotFoundException exception. It just ignores that declaration.
ignoreResourceNotFound = false
If that resource or property file is not available in the classpath, it throws FileNotFoundException exception.  As “false” is default value to this attribute, it is similar to without using this attribute.
@PropertySource(value = “classpath:database.properties”,ignoreResourceNotFound=true)
public class AppConfig {
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *