Skip to content

Spring not calling the default constructor

I have made a simple spring boot application:

public class DemoApplication {

    public static void main(String[] args) {

        ConfigurableApplicationContext context=, args);
        Student student = context.getBean(Student.class);

public class Student {
    private int id;
    private String name;

    public void Student(){
        id = 1;

Here I have put @Component annotation on the Student class. So I can get the student object from the application context. But the id and name
are not initialized as per the default constructor. What could be the reason for this? Does spring not call the default constructor automatically? If not, how is it constructing the object and putting in the
applicationContext? I have also provided the setters and getters in this class. But still, the getName method is returning null.


A constructor in Java should have following rules:

  1. Name should match class name
  2. Constructor should not have a return type
  3. compiler generates default constructor if there is no explicit declaration(user written constructor that looks exactly like a default one is not called default constructor)

In your code you have added return type which makes it a method , since there is no constructor written it is calling a default constructor generated by the compiler.

public Student(){
   id = 1;

Removing void should fix the issue ,however this is a user defined constructor