I have just started learning Spring Boot. I have an error in my code which says
Error creating bean with name 'alien' defined in file [E:\Programing\Java\boot\Project1\target\classes\com\example\demo\Alien.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.example.demo.Alien]: Constructor threw exception; nested exception is java.lang.NullPointerException: Cannot invoke "com.example.demo.Laptop.compile()" because "this.laptop" is null
Below is my code
MainClass
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class Project1Application {
public static void main(String[] args) {
ConfigurableApplicationContext context= SpringApplication.run(Project1Application.class, args);
Alien a=context.getBean(Alien.class);
a.show();
}
}
Alien Class
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
@Component
public class Alien {
private int id;
private String name;
private String tech;
@Autowired
private Laptop laptop;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTech() {
return tech;
}
public void setTech(String tech) {
this.tech = tech;
}
public void show() {
System.out.println("in show..........");
}
public Alien() {
super();
System.out.println("Object Created......");
laptop.compile();
}
}
Laptop class
package com.example.demo;
import org.springframework.stereotype.Component;
@Component
public class Laptop {
private int lid;
private String brand;
@Override
public String toString() {
return "Laptop [lid=" + lid + ", brand=" + brand + "]";
}
public int getLid() {
return lid;
}
public void setLid(int lid) {
this.lid = lid;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public void compile() {
System.out.println("Compiling..");
}
}