'Can not read properties file value in Spring Configuration class

I am trying to simple spring program that has a class named PersistenceConfig annotated with @Configuration

   @Configuration
   @PropertySource("classpath:application.properties")
   public class PersistanceConfig {
        @Value("${dbPassword}")
        private String dbPassword;

        // Set of Beans and Code

        @Bean
        public DataSource dataSource() {
            DriverManagerDataSource dataSource = new DriverManagerDataSource();
            dataSource.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            dataSource.setUrl("jdbc:sqlserver://localhost;databaseName=GovernmentPayment;integratedSecurity=false;");
            dataSource.setUsername("sa");
            dataSource.setPassword(dbPassword);
            return dataSource;
        } 


        @Bean
        public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
            return new PropertySourcesPlaceholderConfigurer();
        }
   }

When i run my program, the value dbPassword is always null but if i try to read the same value inside one my Controllers it reads the value without any issues. I have tried autowiring Environment variable and using it instead of @Value but it didn't work either. (Spring didn't inject value to the Environment Variable)

I am using Spring 4

What is basically want is to externalize the database username and password in a separate property file.



Solution 1:[1]

i don't see any problem with given code.i wrote a simple unit test to your class to prove it works.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=PersistanceConfig.class)
public class PersistanceConfigTest {

    @Autowired
    private DriverManagerDataSource dataSource;

    private final String password = "mydbPassword";


    @Test
    public void testDriverManagerDataSourcePassword() {
        System.out.println("dataSource Password :: " + dataSource.getPassword());
        assertNotNull(dataSource);
        assertTrue(password.equals(dataSource.getPassword()));
    }

}

assuming you have application.properties in src/main/resources and dbPassword=mydbPassword is presented in that file.

Solution 2:[2]

Credit goes to Chad Darby

This is an issue with Spring versions.

If you are using Spring 4.2 and lower, you will need to add the code in marked with(**).

package com.luv2code.springdemo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
@Configuration
// @ComponentScan("com.luv2code.springdemo")
@PropertySource("classpath:sport.properties")
public class SportConfig {
    
    // add support to resolve ${...} properties
  **@Bean
    public static PropertySourcesPlaceholderConfigurer
                    propertySourcesPlaceHolderConfigurer() {
        
        return new PropertySourcesPlaceholderConfigurer();
    }**
    
    // define bean for our sad fortune service
    @Bean
    public FortuneService sadFortuneService() {
        return new SadFortuneService();
    }
    
    // define bean for our swim coach AND inject dependency
    @Bean
    public Coach swimCoach() {
        SwimCoach mySwimCoach = new SwimCoach(sadFortuneService());
        
        return mySwimCoach;
    }
    
}
````
In Spring 4.3 and higher, they removed this requirement. As a result, you don't need this code.

Solution 3:[3]

I have solved this by moving that two annotations to the main file.

package com.luv2code.springdemo;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = "com.luv2code.springdemo.SportConfig")
public class SwimJavaConfigDemoApp {

    public static void main(String[] args) {

        // read spring config java class
        AnnotationConfigApplicationContext context = 
                new AnnotationConfigApplicationContext(SportConfig.class);
        
        // get the bean from spring container
        Coach theCoach = context.getBean("swimCoach", Coach.class);
        
        // call a method on the bean
        System.out.println(theCoach.getDailyWorkout());
                
        // call method to get the daily fortune
        System.out.println(theCoach.getDailyFortune());
                    
        // close the context
        context.close();
        
    }

}

Configure the main file.

Use component scan and specified the path to the cofig class.

Next, write some Bean's to the config file.

package com.luv2code.springdemo;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

public class SportConfig {
    
//  define a bean for sad fortune service
    @Bean
    public FortuneService sadFortuneService() {
        return new SadFortuneService();
    }
    
//  define bean for our swim coach and inject dependency
    @Bean
    public Coach swimCoach() {
        return new SwimCoach(sadFortuneService());
    }
}

For futher learning : Component Scan.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sasi Kathimanda
Solution 2 Saddam Hussain
Solution 3