Mukti
Mukti

Reputation: 311

How to property file value in Spring boot config class

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.

Upvotes: 1

Views: 3765

Answers (1)

olexity
olexity

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

Related Questions