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.
CodePudding user response:
A constructor in Java should have following rules:
- Name should match class name
- Constructor should not have a return type
- 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