0

I'm a beginner when I used the usual config and context everything was fine. how to fix it with @SpringBootApplication

Here is the code of the simplest program:

package com.example;

import com.example.domain.Print;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DbApplication {

  public static void main(String[] args) {
    SpringApplication.run(DbApplication.class, args);
    Print print = new Print();
    print.testSayHello();
  }
}
package com.example.domain;

import org.springframework.stereotype.Component;

@Component
public class Test {
    public void sayHello(){
        System.out.println("Hello");
    }
}
package com.example.domain;

import org.springframework.beans.factory.annotation.Autowired;

public class Print {

    @Autowired
    public Test test;

    public void testSayHello(){
        test.sayHello();
    }
}

returns the following Exception:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "com.example.domain.Test.sayHello()" because "this.test" is null
  at com.example.domain.Print.testSayHello(Print.java:11)
  at com.example.DbApplication.main(DbApplication.java:14)

I tried to replace everything with the usual сontext and config, everything worked, but now I need @SpringBootApplication, help pls

2 Answers2

1

Print should also be an @Component.

Felix
  • 1,337
  • 10
  • 10
0

At this point

Print print = new Print();

The Spring framework is not aware at all of the object creation and it won't inject anything, anywhere in the object tree.

If you want to use Spring DI at this point main(), then run() gives back a Spring context:

ApplicationContext ctx = SpringApplication.run(DbApplication.class, args);
Print print = ctx.getBean(Print.class);
PeterMmm
  • 24,152
  • 13
  • 73
  • 111