Java Spring应用程序@autowired返回空指针异常

vye*_*ri5 0 java spring

我是Java Spring IoC的新手,这是我的问题

我有一个FactoryConfig类,包含所有bean和注释@Configuration和@ComponentScan,如下所示.

import org.springframwork.*

@Configuration
@ComponentScan(basePackages="package.name")
public class FactoryConfig {

    public FactoryConfig() {

    }

    @Bean
    public Test test(){
         return new Test();
    }

    //And few more @Bean's
}
Run Code Online (Sandbox Code Playgroud)

我的Test类有一个简单的Print方法

public class Test {

    public void Print() {
        System.out.println("Hello Test");

    }
}
Run Code Online (Sandbox Code Playgroud)

现在,在我的Main Class中,我创建了一个FactoryConfig的ApplicationContentext.(我希望我的所有@Beans都在Factory配置中初始化.但是,当我使用@Autowired访问Test类时,它返回null

我的主要课程

public class Main {

     @Autowired
     protected static Test _autoTest;

     public static void main(String[] args) throws InterruptedException {
          // TODO Auto-generated method stub
     ApplicationContext context = 
               new AnnotationConfigApplicationContext(FactoryConfig.class);

     FactoryConfig config = context.getBean(FactoryConfig.class);

     config.test().Print();  

    // _autoTest.Print();   <--- Im getting NULL Pointer Ex here 
   }

}
Run Code Online (Sandbox Code Playgroud)

@Autowire和使用对象/ bean的正确方法是什么?任何更清楚的解释将非常感激.

Jér*_*e B 8

只有Spring管理的bean才能有@Autowire注释.你的主类不是由Spring管理的:它是由你创建的,而不是在Spring上下文中声明的:Spring对你的类没有任何了解,也没有注入这个属性.

你可以在main方法中访问Test bean:

context.getBean(Test.class).Print();
Run Code Online (Sandbox Code Playgroud)

通常,您从上下文中获取"引导程序",并调用此引导程序来启动您的应用程序.

此外:

  • 在Java上,方法不应以大写字母开头.你的Test类应该有一个print方法,而不是Print.
  • 如果你从Spring开始,你应该尝试Spring Boot