0

I am trying to instantiate the customer class inside the Running class. Although I ANNOTATED IT AS Component, there is a null pointer exception

@Component
public class Running {
@Autowired
CustomerRepository cRep;

@Autowired InvoiceRepository iRep;


public void run() {
Customer c1=new Customer().setAge(25).setBalance(100).setName("xyz");
Customer c2=cRep.save(c1);

}


@SpringBootApplication
@EnableJpaRepositories

public class HelloWorldSpringBootApp {


    @Autowired  static
     Running r1;
public static void main (String[] args ) {

     SpringApplication.run(HelloWorldSpringBootApp.class, args);
     r1.run();
}

I am getting a null pointer exception on r1.run().

halfer
  • 19,824
  • 17
  • 99
  • 186
coder
  • 23
  • 1
  • 4
  • Remove `static` before `Running` – Ori Marko Mar 24 '19 at 11:03
  • I cannot :I get Cannot make a static reference to the non-static field r1 – coder Mar 24 '19 at 11:04
  • r1 cannot be static. Spring only autowires **instance** fields. Get the Running bean out of the context, and then calli t's run() method. Or make it a command-line runner: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-command-line-runner – JB Nizet Mar 24 '19 at 11:12

1 Answers1

1

Spring does not allow you to autowire static fields (see this question). Here is the right way to get a Running instance:

@SpringBootApplication
@EnableJpaRepositories
public class HelloWorldSpringBootApp {


    public static void main(String[] args) {
        ConfigurableApplicationContext applicationContext = SpringApplication.run(HelloWorldSpringBootApp.class, args);
        Running r1 = applicationContext.getBean(Running.class);
        r1.run();
    }
}