【发布时间】:2013-01-20 13:18:02
【问题描述】:
我是 Java 和 Spring 的新手,来自 C# 和 .NET 世界,所以请耐心等待 - 我正在尝试做的事情可能不合时宜...
我正在尝试使用 Java 配置和注释而不是 XML 配置来配置 Spring DI,但是我遇到了一些问题。这适用于独立应用程序,而不是 Web 应用程序。我已经完成了the springsource documentation,据我所知,我的基本配置应该是正确的......但不是。请看下面的代码:
Java 配置注解类:
package birdalerter.common;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import birdalerter.process.ISightingsProcessor;
import birdalerter.process.SightingsProcessor;
@Configuration
@ComponentScan({"birdalerter.process", "birdalerter.common"})
public class AppConfig {
@Bean
@Scope("prototype")
public ISightingsProcessor sightingsProcessor(){
return new SightingsProcessor();
}
}
配置实现 ISightingsProcessor 接口的组件:
package birdalerter.process;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import org.springframework.stereotype.Component;
import birdalerter.domainobjects.IBirdSighting;
@Component
public class SightingsProcessor implements ISightingsProcessor{
private LinkedBlockingQueue<IBirdSighting> queue;
private List<ISightingVisitor> sightingVisitors = new ArrayList<ISightingVisitor>();
public SightingsProcessor(){
}
...
}
配置工厂组件:
package birdalerter.process;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
public class ProcessorFactory {
private ISightingsProcessor sightingsProcessor;
@Autowired
@Required
private void setSightingsProcessor(ISightingsProcessor sightingsProcessor){
this.sightingsProcessor = sightingsProcessor;
}
public ISightingsProcessor getSightingsProcessor(){
return this.sightingsProcessor;
}
}
连接 AnnotationConfigApplicationContext 并测试:
@Test
public void testProcessingDI(){
@SuppressWarnings("resource")
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(AppConfig.class);
context.refresh();
ISightingsProcessor processor = new ProcessorFactory().getSightingsProcessor();
System.out.println(processor);
Assert.assertTrue(processor != null);
}
SightingsProcessor 没有被设置器注入,并且断言失败,因为返回的对象为空。希望我错过了一些非常明显的东西。
提前致谢。
针对 Meriton 编辑:
感谢美利通的回答。
为什么 Spring 不知道新创建的对象? Spring 是否不会在整个应用程序生命周期中维护依赖关系并在创建配置为 bean 的新对象时适当地注入?
老实说,我不想直接使用context.getBean(ISightingsProcessor.class),如果我可以帮助它,我希望在没有手动干预的情况下将依赖项注入到 setter 方法中 - 它看起来更干净。
我使用ProcessorFactory 作为ISightingsProcessor 接口扩展Runnable - 实现对象将作为线程启动。该应用程序将可配置为具有 n* 个线程,每个线程都在循环迭代中启动。我认为不可能(我可能错了,如果有,请告知)在方法声明中包含@Autowired 注释,因此我使用工厂提供注入的ISightingsProcessor 具体类的新实例。
是的,我刚刚查看了 @Scope 注释 - 你是对的,这需要移至 AppConfig @Bean 声明(我在本次编辑中已完成),谢谢。
【问题讨论】:
-
你不应该在 ProcessFactory 中有一个针对 SightingsProcessor 成员的 @Resource 注释吗?
-
它与
ProcessorFactory中的非静态ISightingsProcessor实例有关,如果静态DI 工作正常(尽管有@Scope注释)。
标签: java spring dependency-injection