Rajeswari Reddy
Rajeswari Reddy

Reputation: 193

Load Config File Issue in Spring Boot

I am trying get values for string Constants from config.properties file in Spring boot application. But when i am trying to access those values from java classes and coming as null.

Please find the code as below:

Config.properties file:

## user Details##
user.username=xyz
user.password=123456


##customer Details  ##
customer.username=abc
customer.password=123456

ConfigProp class:

@Component
@PropertySource("classpath:config.properties")
public class ConfigProp {
    @Value("${user.username}")
    private String userName;

    @Value("${user.password}")
    private String password;

    @Value("${customer.username}")
    private String custUserName;

    @Value("${customer.password}")
    private String custPassowrd;
}

Test Class:

public class Test {
    public static void main(String args[]) {
        ConfigProp configProp = new ConfigProp();
        System.out.println(configProp.getUserName());//coming as null
    }
}

SpringBoot App main class:

@SpringBootApplication
public class UserApplication {
    public static void main(String[] args) {
       SpringApplication.run(UserApplication.class, args);
    }
}

I am not getting the issue exactly , why values are not coming. Can anyone please help me on this and let me know in case of any other details required.

Upvotes: 1

Views: 837

Answers (1)

Shanu Gupta
Shanu Gupta

Reputation: 3807

First problem here:

ConfigProp configProp = new ConfigProp();

You are not letting spring maintain this dependency and hence its not recognizing this as bean.

You Testclass can look like this:

public class Test {
    @Autowired
    ConfigProp configProp;

    public static void main(String args[]) {
        System.out.println(configProp.getUserName());//coming as null
    }
}

The second problem here is presence of two main methods. You should write your Test class as Junit test which would look something like this:

@RunWith(SpringRunner.class)
@SpringBootTest
public class Test {

    @Autowired
    ConfigProp configProp;

    @Test
    public void contextLoads() {
        assertEquals("abc", configProp.getCustUserName());
    }

}

Also Test class should be located in src/test/java location.

Upvotes: 1

Related Questions