我试图编写一个简单的应用程序,以查看Spring如何自动装配组件,但是经过一小时的挣扎,我不知道为什么他会向我展示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);
}
}
并且在此方法中发生错误:
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:忘记添加Fizz类
@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:错误跟踪
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)
我在做什么错?好像Spring看到了我的组件但不注入它