[英]@Inject Not Injecting Beans from Application Context
我有一個Java命令行應用程序,它利用了應用程序上下文文件中定義的Bean。 我可以使用下面的ApplicationContextLoader
類將Bean注入到主類中,該類是從main方法調用的:
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
批注時,我得到了Null指針異常。 是否有一種替代/簡便的方法,允許我在整個應用程序中使用@Inject
批注來引用應用程序上下文文件中定義的任何Bean,而無需指定類名甚至不使用上述ApplicationContextLoader類?
應用環境:
<bean id="currentState" class="com.company.integration.sim.State">
</bean>
<bean id="customerSim" class="com.company.integration.sim.CustomerSim">
</bean>
我引用的Bean如下所示:
public class CustomerSim {
@Inject private State currentState;
.
.
.
您可以嘗試使用AutowiredAnnotationBeanPostProcessor
protected void injectDependencies(Object main) {
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(getApplicationContext());
bpp.processInjection(main);
}
我不確定您使用的方法是否應該能正常工作。 另外,如果您開發測試,請考慮改用Spring Test Context框架 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.