【问题标题】:@Inject Not Injecting Beans from Application Context@Inject 不从应用程序上下文中注入 Bean
【发布时间】:2013-08-29 01:40:05
【问题描述】:

我有一个 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);     
}

但是,当我尝试在我的应用程序(不是 Main 类)的其他类中使用 @Inject 注释时,我得到空指针异常。是否有替代/更简单的方法允许我在整个应用程序中使用 @Inject 注释来引用在我的应用程序上下文文件中定义的任何 Bean,而无需指定类名甚至使用上述 ApplicationContextLoader 类?

应用程序上下文:

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

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

我引用 Beans 如下,它是空的:

public class CustomerSim {

@Inject private State currentState;
.
.
.

【问题讨论】:

  • Spring 将注入到任何由 spring 构造的类中。应用程序中的“其他类”必须是应用程序上下文中的 bean,以便 spring 处理依赖关系。
  • “其他类”在应用程序上下文文件中定义为 Bean,但当我尝试引用它们时为空?
  • 你需要展示你是如何引用其他类的。考虑添加一些代码,以显示 1. 如何获得对其他类的引用和 2. Null 引用。
  • 请用@Inject显示你的上下文和一个类的例子。
  • 请检查 @Inject 注释的导入 - 也许你有被 maven 或其他东西拾取的 Guice 框架。

标签: spring dependency-injection


【解决方案1】:

您可以尝试使用 AutowiredAnnotationBeanPostProcessor

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

我不确定您使用的方法是否应该有效。此外,如果您开发测试,请考虑改用Spring Test Context framework

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-31
    • 2011-05-07
    • 1970-01-01
    • 2019-08-15
    • 1970-01-01
    • 1970-01-01
    • 2013-04-27
    • 1970-01-01
    相关资源
    最近更新 更多