Reputation: 311
How to use a application.properties file in Config class
datasource.username=test
Config.class
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "abcFactory",
transactionManagerRef = "abcmanager",
basePackages = { "com.emp.repository" })
public class EmpConfig {
@Value("${datasource.username}")
String username;
@Bean(name = "empDataSource")
public DataSource empDataSource(String url, String userName, String pwd) {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("XXX");
dataSource.setUrl(url);
dataSource.setUsername(userName);
dataSource.setPassword(pwd);
return dataSource;
}
}
How can i pass the property in to the username set field.
Upvotes: 1
Views: 3765
Reputation: 105
Depending on how you initialized your app, but normally you would put something like
@EnableAutoConfiguration
@PropertySource("classpath:application.properties")
@ComponentScan
@SpringBootApplication
@EnableTransactionManagement
Make sure you have one of these in your configs
@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
Then you can access values like this
@Value("${datasource.username}")
@NotNull //optional
String username;
Upvotes: 1