简体   繁体   English

Spring 没有调用默认构造函数

[英]Spring not calling the default constructor

I have made a simple spring boot application:我制作了一个简单的 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";
    }

Here I have put @Component annotation on the Student class. So I can get the student object from the application context.在这里,我在学生 class 上添加了 @Component 注解。所以我可以从应用程序上下文中获取学生 object。 But the id and name但是id和名字
are not initialized as per the default constructor.未根据默认构造函数进行初始化。 What could be the reason for this?这可能是什么原因? Does spring not call the default constructor automatically? spring不会自动调用默认构造函数吗? If not, how is it constructing the object and putting in the如果不是,它是如何构建 object 并放入
applicationContext?应用上下文? I have also provided the setters and getters in this class. But still, the getName method is returning null.我还在这个 class 中提供了 setter 和 getter。但是,getName 方法仍然返回 null。

A constructor in Java should have following rules: Java 中的构造函数应具有以下规则:

  1. Name should match class name名称应匹配 class 名称
  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删除void应该可以解决问题,但这是用户定义的构造函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM