I\'m trying to learn how to read properties file using spring. After an internet searching I found that I can use @value
and @PropertySource
annota
Nice reply given by @Ian Sparkes . Adding some of my inputs here. Configuring the PropertySourcesPlaceholderConfigurer is not mandatory. I am able to get the value from my properties file and set it to the filed variable of my main Configuration class without it.
There is also another way to get the values of your keys in the properties file. Use org.springframework.core.env.Environment class . This class automatically loads all the key-value pairs in properties file that is in class path.
Example :
@Configuration
@ComponentScan(basePackages="com.easy.buy")
@PropertySource({"classpath:config.properties","classpath:props/db-${env}-config.properties",
"classpath:props/app-${env}-config.properties"})
public class CatalogServiceConfiguration {
Logger logger = LoggerFactory.getLogger(CatalogServiceConfiguration.class);
//This object loads & holds all the properties in it as key-pair values
@Autowired
private Environment env;
/**
* Instantiate the DataSource bean & initialize it with db connection properties
* @return
*/
@Bean(name="basicDataSource")
public BasicDataSource basicDataSource() {
String dbUrl = env.getProperty("db.url");
String dbUser = env.getProperty("db.user");
String dbPwd = env.getProperty("db.pwd");
String driver = env.getProperty("db.driver");
logger.info("Initializing CatalogServiceConfiguration");
logger.info("dbUrl=" + dbUrl);
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName(driver);
ds.setUrl(dbUrl);
ds.setUsername(dbUser);
ds.setPassword(dbPwd);
return ds;
}
}