繁体   English   中英

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

[英]Java Spring application @autowired returns null pointer exception

我对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
}

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

public class Test {

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

    }
}

现在,在我的主类中,Ive创建了FactoryConfig的ApplicationContentext。 (我期望工厂配置中的所有@Beans都将被初始化。但是,当我使用@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 
   }

}

@Autowire和使用对象/ bean的正确方法是什么? 任何更清晰的解释将不胜感激。

只有Spring管理的bean才能具有@Autowire注释。 您的主类不是由Spring管理的:它是由您创建的,并且未在Spring上下文中声明:Spring对您的类一无所知,并且不会注入该属性。

您可以使用以下方法在主要方法中访问Test bean:

context.getBean(Test.class).Print();

通常,您会从上下文中获得一个“引导程序”,并调用该引导程序来启动您的应用程序。

此外:

  • 在Java上,方法不应以大写开头。 您的Test类应该具有print方法,而不是Print
  • 如果您从Spring开始,则应该尝试Spring Boot

Spring不管理您的Main类,这就是为什么您得到Nullpointer Exception的原因。 使用ApplicationContext加载bean,您可以像已经做的那样获取bean和访问Methods-

ApplicationContext context = 
           new AnnotationConfigApplicationContext(FactoryConfig.class);

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

 config.test().Print();  

删除受保护的静态参数Test _autoTest;

你的班

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

对Spring不可见。 尝试向其添加适当的注释,例如@Component

原因是您的Main不是由Spring管理的。 将其作为Bean添加到您的配置中:

import org.springframwork.*

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

    public FactoryConfig() {

    }

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

    @Bean
    public Main main(){
         return new Main();
    }

    //And few more @Bean's
}

然后,您可以按以下方式编辑main()

public class Main {

     @Autowired
     protected Test _autoTest;

     public static void main(String[] args) throws InterruptedException {
         ApplicationContext context = 
               new AnnotationConfigApplicationContext(FactoryConfig.class);

         Test test = context.getBean(Test.class);
         Main main = context.getBean(Main.class);

         test.Print();  
         main._autoTest.Print();
     }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM