Spring @不从应用程序上下文注入bean

Spring @不从应用程序上下文注入bean,spring,dependency-injection,Spring,Dependency Injection,我有一个java命令行应用程序,它使用应用程序上下文文件中定义的bean。我能够使用以下从main方法调用的ApplicationContextLoader类将bean注入到主类中: public class ApplicationContextLoader { private ConfigurableApplicationContext applicationContext; public ConfigurableApplicationContext getApplicat

我有一个java命令行应用程序,它使用应用程序上下文文件中定义的bean。我能够使用以下从main方法调用的
ApplicationContextLoader
类将bean注入到主类中:

public class ApplicationContextLoader {

    private ConfigurableApplicationContext applicationContext;

    public ConfigurableApplicationContext getApplicationContext() {
        return applicationContext;
    }

    protected void loadApplicationContext(String... configLocations) {
        applicationContext = new ClassPathXmlApplicationContext(configLocations);
        applicationContext.registerShutdownHook();
    }

    protected void injectDependencies(Object main) {
        getApplicationContext().getBeanFactory().autowireBeanProperties(main, AutowireCapableBeanFactory.AUTOWIRE_NO, false);
    }

    public void load(Object main, String... configLocations) {
        loadApplicationContext(configLocations);
        injectDependencies(main);
    }
}

public static void main(String[] args) throws IOException {
        DataGeneratorTestRunner dataGeneratorTestRunner = new DataGeneratorTestRunner();
        dataGeneratorTestRunner.launchTests(args, APPLICATION_CONTEXT);
        System.exit(0);
} 

public void launchTests(String[] args, String applicationContext) throws IOException{
            acl  = new ApplicationContextLoader();      
            acl.load(this, applicationContext);     
}
但是,当我尝试在我的应用程序中的其他类(不是主类)中使用
@Inject
注释时,会出现空指针异常。是否有其他/更简单的方法允许我在整个应用程序中使用
@Inject
注释来引用在应用程序上下文文件中定义的任何Bean,而不必指定类名,甚至不必使用上述ApplicationContextLoader类

应用程序上下文:

<bean id="currentState" class="com.company.integration.sim.State">
</bean>

    <bean id="customerSim" class="com.company.integration.sim.CustomerSim">
    </bean>

您可以尝试使用AutoWiredNotationBeanPostProcessor

 protected void injectDependencies(Object main) {
    AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
    bpp.setBeanFactory(getApplicationContext());
    bpp.processInjection(main);
  }

我不确定你使用的方法是否有效。此外,如果您开发测试,请考虑使用。

Spring将注入到由Spring构建的任何类中。应用程序中的“其他类”必须是应用程序上下文中的bean,以便spring处理依赖关系。“其他类”在应用程序上下文文件中定义为bean,但在我尝试引用它们时为null?您需要显示如何引用其他类。考虑添加一些显示1的代码。如何获得对其他类和2的引用。空引用。请显示您的上下文和带有
@Inject
的类的示例。请检查
@Inject
注释的导入-可能您有maven拾取的Guice framework或其他东西。
 protected void injectDependencies(Object main) {
    AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
    bpp.setBeanFactory(getApplicationContext());
    bpp.processInjection(main);
  }