1

How to use a application.properties file in Config class

application.properties

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.

Community
  • 1
  • 1
Mukti
  • 291
  • 2
  • 5
  • 13

1 Answers1

1

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;
olexity
  • 105
  • 4
  • 1
    you wouldn't need `@EnableAutoConfiguration`, `@ComponentScan` and `@PropertySource("classpath:application.properties")` since `@SpringBootApplication` already has the first two incorporated. `application.properties` is scanned for properties by default so you don't need to add it as a property source. And if you have spring boot starter in your pom you wouldn't need `PropertySourcesPlaceholderConfigurer` either. – Rahul Sharma Apr 21 '16 at 22:59
  • if i am using the following, it is not working. @Value("${datasource.username}") @NotNull //optional String username; – Mukti Apr 22 '16 at 01:31
  • Here: http://stackoverflow.com/questions/36635163/spring-boot-externalizing-properties-not-working/36635367#36635367 you can find an example of a working Spring Boot project with both internal and external properties. @RahulSharma is correct in all his comments. – Marco Tedone Apr 22 '16 at 06:46
  • @Mukti you need to add the code for us to see what's happening – Rahul Sharma Apr 22 '16 at 16:27
  • @RahulSharma, i have updated the code above, still getting on @Value("${datasource.username}") – Mukti Apr 25 '16 at 13:28