ThivankaW
ThivankaW

Reputation: 540

Attributes in property file returns null

I have a DBconfig property file with the attributes as follows;

DB_url = jdbc:mysql://localhost:8080/studentdb
DB_username = root
DB_password = abc123

i want to print the values inside my a Database service class (DBconnect.class),

@PropertySource("classpath:DBconfig.properties")
public class DBconnection {

    private Connection con= null;

    @Value("${DB_url}")
    private String url;

    @Value("${DB_username}")
    private String username;

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

    public DBconnection() {

        System.out.println(url);      // Output = null
        System.out.println(username); // Output = null
        System.out.println(password); // Output = null

    }

}

the exact same code works and the values are printed when i try to print the values from the controller;

@Controller
@PropertySource("classpath:DBconfig.properties")
public class HomeController {

    @Value("${DB_url}")
    private String url;

    @Value("${DB_username}")
    private String username;

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

    @RequestMapping(value="/", method=RequestMethod.GET)
    public String Message() {


        System.out.println(url); //jdbc:mysql://localhost:8080/studentdb      
        System.out.println(username); //root
        System.out.println(password); //abc123

        DBconnection conn = new DBconnection();
        return "home";
    }

}

why does it work in the controller and not my Service package ? how do i get this to work in my service package ?

I only have 2 packages in src/main/java;

controller package( HomeController.class included) service package (DBconnect.class included)

src/main/resources contain the DBconfig.properties file

Upvotes: 0

Views: 42

Answers (1)

Mạnh Quyết Nguyễn
Mạnh Quyết Nguyễn

Reputation: 18235

When you use @Value, the Spring container when inject the value via BeanPostProcessor

Hence in your constructor, your value are all null.

In your controller, you can access the injected value because the bean now fully instantiated

If you want to access your injected value in service, add @Configuration to your class and add @PostConstruct annotation to your method:

@Configuration
@PropertySource("classpath:DBconfig.properties")
public class DBconnection {

@PostConstruct
public void init() {
        System.out.println(url); //jdbc:mysql://localhost:8080/studentdb      
        System.out.println(username); //root
        System.out.println(password); //abc123
}
}

Upvotes: 1

Related Questions