Injecting dependencies in a prototype bean

I am using lookup method injection in Spring 3 to inject a prototype bean into a singleton bean as described in the Spring docs here. Inside my prototype bean I have an @Autowired dependency on another bean declared in my applicationContext.xml. The lookup method injection seems to be working properly in that my prototype bean is being injected into my singleton bean, however, the prototype's dependency is not getting injected at all. Can dependencies be injected into the prototype bean in a normal way when the prototype is returned via lookup method? If not, what is the preferred way to do this?

Edit : The bean definitions are as follows:

<bean id="jobRouter" class="com.ccn.JobRouter">
   <lookup-method name="createJobConsumer" bean="jobConsumer"/>
</bean>

<bean id="jobConsumer" class="com.ccn.JobConsumer" scope="prototype"/>

<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
   <property name="corePoolSize" value="5" />
   <property name="maxPoolSize" value="100" />
   <property name="WaitForTasksToCompleteOnShutdown" value="true" />
</bean>

JobRouter

public abstract class JobRouter {

   private LinkedHashMap<String, JobConsumer> jobRoutingMap = new LinkedHashMap<String, JobConsumer>();

   public void add(Job Job) {
      if(!jobRoutingMap.containsKey(job.getObjectKey())){
             jobRoutingMap.put(job.getObjectKey(), createJobConsumer());
      }
      //Hand off job to consumer
      JobConsumer jobConsumer = jobRoutingMap.get(job.getObjectKey());
      jobConsumer.add(job);
   }

   protected abstract JobConsumer createJobConsumer();
}

JobConsumer

public class JobConsumer {

   @Autowired private TaskExecutor taskExecutor;

   private LinkedBlockingQueue<Job> jobQueue = new LinkedBlockingQueue<Job>();  

   public JobConsumer() {
      taskExecutor.execute(new JobQueueMonitor());
   }

   public boolean add(Job job) {
      if(!jobQueue.contains(job)){
         return jobQueue.add(job);
      }
      return true;
   }

   private class JobQueueMonitor implements Runnable{
      @Override 
      public void run() {
         ...
      }
   }
}

I figured out that the dependency inside my prototype bean was, in fact, being injected properly. The problem was that I was trying to access the dependency inside the constructor (see the JobConsumer constructor in my code above) before the dependency was injected and it was obviously null. I moved the code from the JobConsumer constructor into a @PostConstruct annotated method and it worked as expected.

链接地址: http://www.djcxy.com/p/22690.html

上一篇: Spring:方法注入查找如何使用它?

下一篇: 注入原型bean中的依赖关系