0

I tried to write simple app to see how the Spring is autowiring the components, but after hour of struggling i can't figure out why is he show me nullptrexception.

@SpringBootApplication
@ComponentScan(basePackageClasses = {FizzBuzzAlgorithm.class, NumberPrinter.class})
public class TestEngineApplication {


    private static NumberPrinter numberPrinter = new NumberPrinter();

    public static void main(String[] args) {
        ApplicationContext context  = SpringApplication.run(TestEngineApplication.class, args);

        System.out.println("Contains A  " + context.containsBeanDefinition("fizzBuzzAlgorithm")); // prints true
        System.out.println("Contains B  " + context.containsBeanDefinition("numberPrinter")); // prints true
        doSth();

    }

    public static void doSth(){
        numberPrinter.printValues(1,100);
    }
}

And in this method occures error:

public class NumberPrinter {

@Autowired
FizzBuzzAlgorithm fizzBuzzAlgorithm;


public void printValues(int lowerBound, int upperBound){

    if(lowerBound < 1){
        throw new RuntimeException("Value cannot be less then 1");
    }
    for(int i = lowerBound; i < upperBound ; i++){
        System.out.println(fizzBuzzAlgorithm.calculate(i)); <-- fizzbuzzAlg. is null
    }
}

}

@EDIT: Forgot to add a Fizz class

@Component("fizzBuzzAlgorithm")
public class FizzBuzzAlgorithm {

private static final int FIZZ = 3;
private static final int BUZZ = 5;


public String calculate(int number){

    if(number%FIZZ == 0){
        return "FIZZ";
    }
    else if(number%BUZZ == 2){
        return "BUZZ";
    }
    return Integer.toString(number);
}

}

@EDIT: Error trace

    018-07-11 11:12:16.372  INFO 11516 --- [           main] c.e.testEngine.TestEngineApplication     : Started TestEngineApplication in 1.773 seconds (JVM running for 2.14)
Exception in thread "main" java.lang.NullPointerException
Contains A  true
    at com.example.testEngine.FizzBuzz.NumberPrinter.printValues(NumberPrinter.java:19)
Contains B  true
    at com.example.testEngine.TestEngineApplication.doSth(TestEngineApplication.java:31)
    at com.example.testEngine.TestEngineApplication.main(TestEngineApplication.java:26)

What am i doing wrong? It seems like Spring see my component but dont inject it

Mikkes23
  • 29
  • 2
  • How NumberPrinter annotated? is it handle by spring and how you create it? – Ori Marko Jul 11 '18 at 09:08
  • Can you add the stacktrace of the exception? – Herr Derb Jul 11 '18 at 09:12
  • It is created manually in main method (I can't autowire it cause it is static filed) – Mikkes23 Jul 11 '18 at 09:12
  • You created it manually, so there you have it, the reason why you get a NPE. Additionally to the chosen duplicate, this question is also related: https://stackoverflow.com/questions/1018797/can-you-use-autowired-with-static-fields – g00glen00b Jul 11 '18 at 10:56

0 Answers0