Skip to content
Advertisement

Spring not calling the default constructor

I have made a simple spring boot application:

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {

        ConfigurableApplicationContext context= SpringApplication.run(DemoApplication.class, args);
        Student student = context.getBean(Student.class);
      System.out.println(student.getName());

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

    public void Student(){
        id = 1;
        name="asd";
    }

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.

Advertisement

Answer

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;
   name="asd";
}

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

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement