Spring 没有调用默认构造函数

Spring not calling the default constructor

我制作了一个简单的spring启动应用程序:

@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";
    }

在这里,我在 Student class 上添加了 @Component 注释。所以我可以从应用程序上下文中获取学生对象。但是 id 和 name
没有按照默认构造函数进行初始化。这可能是什么原因? spring 不会自动调用默认构造函数吗?如果不是,它是如何构造对象并放入
applicationContext 的?我还在这个 class 中提供了 setter 和 getter。但是,getName 方法仍然返回 null。

Java 中的构造函数应具有以下规则:

  1. 名字应该匹配 class 名字
  2. 构造函数不应有 return 类型
  3. 如果没有显式声明,编译器会生成默认构造函数(用户编写的看起来与默认构造函数完全一样的构造函数不称为默认构造函数)

在您的代码中,您添加了 return 类型,这使它成为一个方法,因为没有编写构造函数,它调用编译器生成的默认构造函数。

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

删除 void 应该可以解决问题,但这是用户定义的构造函数